Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a dataframe with over 200 columns. The issue is as they were generated the order is

['Q1.3','Q6.1','Q1.2','Q1.1',......] 

I need to sort the columns as follows:

['Q1.1','Q1.2','Q1.3',.....'Q6.1',......] 

Is there some way for me to do this within Python?

like image 553
pythOnometrist Avatar asked Jun 16 '12 21:06

pythOnometrist


People also ask

How do I rearrange the order of columns in pandas?

Reorder Columns using Pandas . Another way to reorder columns is to use the Pandas . reindex() method. This allows you to pass in the columns= parameter to pass in the order of columns that you want to use.

How do you rearrange columns in a DataFrame in Python?

You need to create a new list of your columns in the desired order, then use df = df[cols] to rearrange the columns in this new order.

How replace column values in pandas based on multiple conditions?

You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.


1 Answers

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.

like image 99
BrenBarn Avatar answered Sep 20 '22 02:09

BrenBarn