【问题标题】:Count unique values that are grouped by in Python计算在 Python 中分组的唯一值
【发布时间】:2017-07-24 06:43:15
【问题描述】:

我正在使用 python 数据库并且正在使用 pandas。目前我的数据库显示如下:

Employer        Account_Num
AAA             123
BBB             456
AAA             789
AAA             123
BBB             101
CCC             112

我可以将它放入一个计算所有 Account_Num 的表中,如下所示:

Employer   Account_Num
AAA        3
BBB        2
CCC        1

我用这段代码实现了上面的:

bigdata.groupby(['Employer'])[['Account_Num']].count()

但我只需要计算唯一的 Account_Num。应该是这样的:

Employer   Account_Num
AAA        2
BBB        2
CCC        1

实现这一目标的最佳方法是什么?谢谢!

【问题讨论】:

    标签: python pandas count group-by unique


    【解决方案1】:

    您正在寻找nunique()

    df.groupby('Employer').Account_Num.nunique()
    

    演示

    >>> df.groupby('Employer').Account_Num.nunique()
    
    Employer
    AAA    2
    BBB    2
    CCC    1
    Name: Account_Num, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 2022-08-22
      • 2012-02-10
      • 2014-04-16
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多