根据列表对 pandas 数据框进行排序 [英] sort pandas dataframe based on list
问题描述
我想对以下数据框进行排序:
I would like to sort the following dataframe:
Region LSE North South
0 Cn 33.330367 9.178917
1 Develd -36.157025 -27.669988
2 Wetnds -38.480206 -46.089908
3 Oands -47.986764 -32.324991
4 Otherg 323.209834 28.486310
5 Soys 34.936147 4.072872
6 Wht 0.983977 -14.972555
我想对它进行排序,以便根据列表对LSE列进行重新排序:
I would like to sort it so the LSE column is reordered based on the list:
lst = ['Oands','Wetnds','Develd','Cn','Soys','Otherg','Wht']
当然,其他列也将需要相应地重新排序.熊猫有什么办法吗?
of, course the other columns will need to be reordered accordingly as well. Is there any way to do this in pandas?
推荐答案
pandas 0.15版中对Categorical
的改进支持使您可以轻松地做到这一点:
The improved support for Categorical
s in pandas version 0.15 allows you to do this easily:
df['LSE_cat'] = pd.Categorical(
df['LSE'],
categories=['Oands','Wetnds','Develd','Cn','Soys','Otherg','Wht'],
ordered=True
)
df.sort('LSE_cat')
Out[5]:
Region LSE North South LSE_cat
3 3 Oands -47.986764 -32.324991 Oands
2 2 Wetnds -38.480206 -46.089908 Wetnds
1 1 Develd -36.157025 -27.669988 Develd
0 0 Cn 33.330367 9.178917 Cn
5 5 Soys 34.936147 4.072872 Soys
4 4 Otherg 323.209834 28.486310 Otherg
6 6 Wht 0.983977 -14.972555 Wht
如果这只是临时排序,则将LSE列保留为
Categorical
可能不是您想要的,但是如果此顺序是
您希望能够利用几次的东西
在不同的情况下,Categoricals
是一个很好的解决方案.
If this is only a temporary ordering then keeping the LSE column as
a Categorical
may not be what you want, but if this ordering is
something that you want to be able to make use of a few times
in different contexts, Categoricals
are a great solution.
在pandas
的更高版本中,sort
已被sort_values
替换,因此您需要:
In later versions of pandas
, sort
, has been replaced with sort_values
, so you would need instead:
df.sort_values('LSE_cat')
这篇关于根据列表对 pandas 数据框进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!