【问题标题】:sort pandas value_counts() primarily by descending counts and secondarily by ascending values对 pandas value_counts() 进行排序,主要是按计数降序,其次是按升序排列
【发布时间】:2015-10-04 13:28:48
【问题描述】:

将 value_counts() 应用于 pandas 中的系列时,默认情况下计数按降序排序,但值不会在每个计数中排序。

如何让每个相同计数中的值按升序排序?

apples    5
peaches   5
bananas   3
carrots   3
apricots  1

【问题讨论】:

  • 您能否展示具有预期输出的 DataFrame 或 Series 示例?
  • 你说的是索引值吗?不幸的是,默认排序总是按我发现的降序排序

标签: python-3.x pandas


【解决方案1】:

value_counts 的输出本身就是一个序列(就像输入一样),因此您可以像使用任何序列一样使用所有标准排序选项。例如:

df = pd.DataFrame({ 'fruit':['apples']*5  + ['peaches']*5 + ['bananas']*3 +
                            ['carrots']*3 + ['apricots'] })

df.fruit.value_counts().reset_index().sort([0,'index'],ascending=[False,True])

      index  0
0    apples  5
1   peaches  5
2   bananas  3
3   carrots  3
4  apricots  1

默认情况下,我实际上得到了相同的结果,所以这里有一个ascending=[False,False] 的测试,以证明这实际上是按照建议的那样工作。

df.fruit.value_counts().reset_index().sort([0,'index'],ascending=[False,False])

      index  0
1   peaches  5
0    apples  5
3   carrots  3
2   bananas  3
4  apricots  1

实际上,我对这里的升序和降序到底需要什么输出有点困惑,但无论如何,这里有 4 种可能的组合,您可以通过更改 ascending 关键字参数来获得它。

【讨论】:

  • 谢谢!我缺少的是 reset_index() 部分。你能在这里解释一下它的作用吗?
  • 还需要添加例如在 to_csv: , header=False , index=False
  • @eyaler reset_index 将现有索引转换为列,这使得排序更容易。 sort 可以对索引或列进行操作,但不能同时对两者进行操作(据我所知)
猜你喜欢
  • 2016-10-18
  • 2021-06-10
  • 2020-11-09
  • 2011-07-30
  • 2015-08-30
  • 2018-05-03
  • 2020-10-05
  • 1970-01-01
相关资源
最近更新 更多