简体   繁体   中英

How to sort column names in pandas dataframe by specifying keywords

Specify any keyword in list or dict format as follows
Is it possible to sort columns in a data frame?

df = pd.DataFrame ({  
    "col_cc_7": [0, 0, 0],  
    "col_aa_7": [1, 1, 1],  
    "col_bb_7": [2, 2, 2]})

# before  
col_cc_7, col_aa_7, col_bb_7  
0,        1,        2  
0,        1,        2  
0,        1,        2  

# sort  
custom_sort_key = ["aa", "bb", "cc"]  
# ... sort codes ...  

# after  
col_aa_7, col_bb_7, col_cc_7  
1, 2, 0  
1, 2, 0  
1, 2, 0  

For me, your question is a little confusing.

If you only want to sort your columns values, a simple google search would do the trick, if not, I could not understand the question.

df=  df.sort_values(by=['col','col2', "col3"],ascending=[True,True,False]) 

The by= sets the order of the sorting, and the ascending is self explanatory.

We can split by the middle value and create a dictionary of your columns, then apply a sort before we assign this back. I've added some extra columns not in your sort to show what will happen to them.

df = pd.DataFrame ({  
    "col_cc_7": [0, 0, 0],  
    "col_aa_7": [1, 1, 1],  
    "col_bb_7": [2, 2, 2],
    "col_ee_7": [2, 2, 2],
    "col_dd_7": [2, 2, 2]})

custom_sort_key = ["bb", "cc", "aa"]  

col_dict = dict(zip(df.columns,[x.split('_')[1] for x in df.columns.tolist()]))

#{'col_cc_7': 'cc',
# 'col_aa_7': 'aa',
# 'col_bb_7': 'bb',
# 'col_ee_7': 'ee',
# 'col_dd_7': 'dd'}
d = {v:k for k,v in enumerate(custom_sort_key)}


# this will only work on python 3.6 +
new_cols = dict(sorted(col_dict.items(), key=lambda x: d.get(x[1], float('inf'))))

df[new_cols.keys()]
       col_bb_7  col_cc_7  col_aa_7  col_ee_7  col_dd_7
0         2         0         1         2         2
1         2         0         1         2         2
2         2         0         1         2         2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM