Re-ordering columns in pandas dataframe based on column name [duplicate] Re-ordering columns in pandas dataframe based on column name [duplicate] python python

Re-ordering columns in pandas dataframe based on column name [duplicate]


df = df.reindex(sorted(df.columns), axis=1)

This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pandas.


You can also do more succinctly:

df.sort_index(axis=1)

Make sure you assign the result back:

df = df.sort_index(axis=1)

Or, do it in-place:

df.sort_index(axis=1, inplace=True)


You can just do:

df[sorted(df.columns)]

Edit: Shorter is

df[sorted(df)]