Sorting 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.

Leave a Comment