2

Recently updated to pandas 0.17.0 and I'm trying to order the columns in my dataframe alphabetically.

Here are the column labels as they currently are:

['UX2', 'RHO1', 'RHO3', 'RHO2', 'RHO4', 'UX1', 'UX4', 'UX3']

And I want them like this:

['RHO1', 'RHO2', 'RHO3', 'RHO4', 'UX1', 'UX2', 'UX3', 'UX4']

The only way I've been able to do this is following this from 3 years ago: How to change the order of DataFrame columns?

Is there a built-in way to do this in 0.17.0?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Greg Brown
  • 1,251
  • 1
  • 15
  • 32

3 Answers3

3

To sort the columns alphabetically here, you can just use sort_index:

df.sort_index(axis=1)

The method returns a reindexed DataFrame with the columns in the correct order.

This assumes that all of the column labels are strings (it won't work for a mix of, say, strings and integers). If this isn't the case, you may need to pass an explicit ordering to the reindex method.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
1

You can just sort them and put them back. Suppose you have this:

df = pd.DataFrame()
for i, n in enumerate(['UX2', 'RHO1', 'RHO3', 'RHO2', 'RHO4', 'UX1', 'UX4', 'UX3']):
    df[n] = [i]

It looks like this:

df
   UX2  RHO1  RHO3  RHO2  RHO4  UX1  UX4  UX3
0    0     1     2     3     4    5    6    7

Do this:

df = df[ sorted(df.columns)]

And you should see this:

df
   RHO1  RHO2  RHO3  RHO4  UX1  UX2  UX3  UX4
0     1     3     2     4    5    0    7    6
Harold Ship
  • 989
  • 1
  • 8
  • 14
1

Create a list of the columns labels in the order you want.

cols = ['RHO1', 'RHO2', 'RHO3', 'RHO4', 'UX1', 'UX2', 'UX3', 'UX4']

Then assign this order to your DataFrame df:

df = df[cols]
elloa
  • 51
  • 3