Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to change the order of DataFrame columns?

I have the following DataFrame (df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

I add more column(s) by assignment:

df['mean'] = df.mean(1)

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?

Answer*

Cancel
2
  • 8
    This was a nice solution, but reindex_axis will be deprecated. I used reindex, and it worked just fine.
    – Jorge
    Commented Aug 8, 2018 at 21:32
  • I may miss something but 1/ you likely forgot to include axis=1 in this second solution to use the columns, not the rows. 2/ In 2020, the reindex solution changes the rows/columns order, but also clears data (NaN everywhere).
    – mins
    Commented Dec 15, 2020 at 10:30