【问题标题】:Sort by Frequency of Values in a Column - Pandas按列中值的频率排序 - Pandas
【发布时间】:2017-11-05 21:51:31
【问题描述】:

我在数据框中有一列

水果
苹果
芒果
香蕉
苹果
芒果
香蕉
苹果
芒果
葡萄

我想按其中出现的值的频率对该列进行排序,所以现在的数据框应该是:

水果
苹果
苹果
苹果
香蕉
香蕉
香蕉
芒果
芒果
葡萄

谢谢!

【问题讨论】:

标签: python sorting pandas


【解决方案1】:

创建一个频率列,然后按频率和水果名称排序。

df.assign(freq=df.apply(lambda x: df.Fruits.value_counts()\
  .to_dict()[x.Fruits], axis=1))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]
Out[593]: 
   Fruits
0   Apple
3   Apple
6   Apple
1   Mango
4   Mango
7   Mango
2  Banana
5  Banana
8  Grapes

使用 groupby 和 count 的类似方法:

df.assign(freq=df.groupby('Fruits')['Fruits'].transform('count'))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]

【讨论】:

  • 这可行,但我有一个多列数据框,那么如何显示所有列?
  • 对于将来引用此帖子的任何人,响应 mLstudent33,使用第一种方法(接受答案的方法)显示所有列,您只需摆脱 ".loc [:,['水果']]"
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 2013-05-20
  • 1970-01-01
相关资源
最近更新 更多