pandas 数据框中的自定义排序 [英] Custom sorting in pandas dataframe
问题描述
我有 python pandas 数据框,其中一列包含月份名称.
I have python pandas dataframe, in which a column contains month name.
如何使用字典进行自定义排序,例如:
How can I do a custom sort using a dictionary, for example:
custom_dict = {'March':0, 'April':1, 'Dec':3}
推荐答案
Pandas 0.15 引入 Categorical Series,它提供了一种更清晰的方法来做到这一点:
Pandas 0.15 introduced Categorical Series, which allows a much clearer way to do this:
首先将月份列设为分类列并指定要使用的排序.
First make the month column a categorical and specify the ordering to use.
In [21]: df['m'] = pd.Categorical(df['m'], ["March", "April", "Dec"])
In [22]: df # looks the same!
Out[22]:
a b m
0 1 2 March
1 5 6 Dec
2 3 4 April
现在,当您对月份列进行排序时,它将根据该列表进行排序:
Now, when you sort the month column it will sort with respect to that list:
In [23]: df.sort_values("m")
Out[23]:
a b m
0 1 2 March
2 3 4 April
1 5 6 Dec
注意:如果一个值不在列表中,它将被转换为 NaN.
对于那些有兴趣的人来说,一个较旧的答案......
An older answer for those interested...
您可以创建一个中间系列,然后set_index
关于这一点:
You could create an intermediary series, and set_index
on that:
df = pd.DataFrame([[1, 2, 'March'],[5, 6, 'Dec'],[3, 4, 'April']], columns=['a','b','m'])
s = df['m'].apply(lambda x: {'March':0, 'April':1, 'Dec':3}[x])
s.sort_values()
In [4]: df.set_index(s.index).sort()
Out[4]:
a b m
0 1 2 March
1 3 4 April
2 5 6 Dec
<小时>
正如所评论的,在较新的熊猫中,系列有一个 replace
方法可以更优雅地做到这一点:
As commented, in newer pandas, Series has a replace
method to do this more elegantly:
s = df['m'].replace({'March':0, 'April':1, 'Dec':3})
略有不同的是,如果存在字典之外的值,则不会提高(它会保持不变).
这篇关于 pandas 数据框中的自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!