给定这个DataFrame和一个列表:
df = pd.DataFrame([['August', 2], ['July', 3], ['Sept', 6]], columns=['A', 'B'])
order = ['July','Sept','August']
df
Out[310]:
A B
1 August 2
0 July 3
2 Sept 6
我想用给定的列表重新排序df['A'],所以最终输出是:
A B
1 July 3
0 Sept 6
2 August 2
是否有任何方法,使我可以排序的列使用字符串列表?
如果可能的话,按前3个字母生成的日期时间排序使用DataFrame.sort_values
和key
参数:
df = df.sort_values('A', key=lambda x: pd.to_datetime(x.str[:3], format='%b'))
print (df)
A B
1 July 3
0 August 2
2 Sept 6
另一个有序分类的解:
order = ['July','Sept','August']
df['A'] = pd.Categorical(df.A, ordered=True, categories=order)
df = df.sort_values('A')
print (df)
A B
1 July 3
2 Sept 6
0 August 2
试一试:
df = pd.DataFrame([['August', 2], ['July', 3], ['Sept', 6]], columns=['A', 'B'])
order = ['July','Sept','August']
df = df.set_index('A')
df = df.reindex(index = order)
df = df.reset_index()