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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.