Python以相反的字母顺序排列数据框列

我目前的数据框列的顺序为


df.columns = ['S1FF', 'S1Ipmax', 'S2POA', 

       ...

       'M04Vpmax', 'M04elec_event', 'M04group', 'M04met_event', 'M04mode',

       'M04validation_1min', 'M04validation_2min', 'M04S1T', 'M04S2T',

       'M04datetime']  # Columns start with S1,S2, M01 to M24

我想以相反的字母顺序对它们进行排序。我现在的代码是


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

我现在的输出是


df.columns = ['M01FF', 'M01Ipmax', 'M02POA', 

       ...

       'S1FF', 'S1Ipmax', 'S2POA']

但我的预期输出是反向字母顺序


df.columns = ['S1FF', 'S1Ipmax', 'S2POA','M01FF', 'M01Ipmax', 'M02POA', 

       ...

       'M23FF', 'M24Ipmax', 'M24POA']


慕容3067478
浏览 126回答 1
1回答

慕标5832272

key通过字符串的第一个值使用参数,这里S和Mwith reverse=True:L = ['M01FF', 'M01Ipmax', 'M02POA', 'S1FF', 'S1Ipmax', 'S2POA']df = pd.DataFrame(columns=L)print (df)Empty DataFrameColumns: [M01FF, M01Ipmax, M02POA, S1FF, S1Ipmax, S2POA]Index: []df = df[sorted(df.columns, key=lambda x: x[0], reverse = True)]print (df)Empty DataFrameColumns: [S1FF, S1Ipmax, S2POA, M01FF, M01Ipmax, M02POA]Index: []编辑:import natsort as nss = ns.natsorted([x for x in df.columns if x[0] == 'S'])m = ns.natsorted([x for x in df.columns if x[0] == 'M'])df = df[s + m]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python