[英]sorting rows in a pandas dataframe in a way which is not alphabetical
我有一些数据框 (df),其中的分类数据以:a、b、c 和“剩余类别”的类别开头。
我想对 dataframe ascending=true 中的月份列进行排序,然后对类别列进行排序,以便它们按以下顺序排列:
c
a
b
“剩余类别”
这可能吗? --> 基本上我想要一个特定列的自定义排序顺序,然后按日期顺序对月份列进行排序。
文档在这里
In [8]: df = DataFrame({'A' : [1,1,1,2,2,3], 'B' : list('bbcdae') })
In [9]: df.dtypes
Out[9]:
A int64
B object
dtype: object
In [10]: df['B'] = pd.Categorical(df['B'],categories=list('ghbaedfc'))
In [11]: df
Out[11]:
A B
0 1 b
1 1 b
2 1 c
3 2 d
4 2 a
5 3 e
In [12]: df.dtypes
Out[12]:
A int64
B category
dtype: object
In [13]: df.sort(['B','A'])
Out[13]:
A B
0 1 b
1 1 b
4 2 a
5 3 e
3 2 d
2 1 c
您可以使用dict并在数据框中添加新的“ sort”列。 看看这个类似的问题熊猫自定义排序
Pandas sort() 已弃用并从 Pandas 版本 0.20 (2017-05-05) 中删除。
Pandas 现在使用 sort_values() 和 sort_index() 代替 sort()。 要按分类顺序获取 df,请使用 pd.Categorical()
df = pd.DataFrame({'Panel':['Left', 'Right', 'Top', 'Bottom','Left'],
Value':[70, 50, 30, 40, 60]})
df['Panel'] = pd.Categorical(df['Panel'],
categories=['Top','Bottom','Left','Right'],ordered=True)
结果
Panel Value
2 Top 30
3 Bottom 40
0 Left 70
4 Left 60
1 Right 50
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.