【问题标题】:How to perform LINQ ThenBy in pandas?如何在熊猫中执行 LINQ ThenBy?
【发布时间】:2017-12-24 03:21:32
【问题描述】:

我有简单的数据:

type age 
A    4   
A    4   
B    4   
A    5   

我想得到

type age count
A    4    2
A    5    1
B    4    1

如何在 panda 中执行这样的事情:df.groupby(['type']) 之后我做了什么 shell?

【问题讨论】:

    标签: python python-3.x pandas grouping


    【解决方案1】:

    让我们将groupby 与“类型”和“年龄”一起使用,然后使用count 和reset_index:

    df.groupby(['type','age'])['age'].count().reset_index(name='count')
    

    输出:

      type  age  count
    0    A    4      2
    1    A    5      1
    2    B    4      1
    

    【讨论】:

      【解决方案2】:

      你也可以

      df.groupby(['type','age']).size().reset_index(name='count')
      

      【讨论】:

      • 我能知道为什么它给出正确答案时被否决了吗?
      猜你喜欢
      • 1970-01-01
      • 2021-03-29
      • 2022-10-19
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多