我目前的数据框列的顺序为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']
1 回答
慕标5832272
TA贡献1966条经验 获得超4个赞
key通过字符串的第一个值使用参数,这里S和Mwith reverse=True:
L = ['M01FF', 'M01Ipmax', 'M02POA', 'S1FF', 'S1Ipmax', 'S2POA']
df = pd.DataFrame(columns=L)
print (df)
Empty DataFrame
Columns: [M01FF, M01Ipmax, M02POA, S1FF, S1Ipmax, S2POA]
Index: []
df = df[sorted(df.columns, key=lambda x: x[0], reverse = True)]
print (df)
Empty DataFrame
Columns: [S1FF, S1Ipmax, S2POA, M01FF, M01Ipmax, M02POA]
Index: []
编辑:
import natsort as ns
s = 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]
添加回答
举报
0/150
提交
取消