在 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}
推荐答案
熊猫0.15引入了分类系列" ,它可以更清晰地做到这一点:
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...
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
如所评论,在新的熊猫中,Series具有 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屋!