【问题标题】:Python: How to use value_counts() inside .agg function in pandas?Python:如何在熊猫的 .agg 函数中使用 value_counts()?
【发布时间】:2022-10-13 20:04:29
【问题描述】:

输入数据框df 看起来像:

item    row
Apple   12
Apple   12
Apple   13
Orange  13
Orange  14
Lemon   14

输出数据框需要

item    unique_row      nunique_row     count
Apple   {12,13}             2            {2,1}
Orange  {13,14}             2            {1,1}
Lemon   {14}                1            {1}

试过的代码:

df.groupby('item', as_index=False)['row'].agg({'unique_row': lambda x: set(x)
                                                ,'nunique_row': lambda x: len(set(x))})

所以在这里,不知道如何在.agg 函数中添加条件来生成列'count'。列 'count' 表示每个行值的 value_count 数量。 任何帮助将不胜感激。谢谢你!

【问题讨论】:

    标签: python-3.x pandas dataframe group-by aggregate-functions


    【解决方案1】:

    您需要转换为列表或设置:

    (df.groupby('item', as_index=False)['row']
       .agg({'unique_row': lambda x: set(x),
             'nunique_row': lambda x: len(set(x)),
             'count': lambda x: list(x.value_counts()), # or set(x.value_counts())
            })
    )
    

    输出:

         item unique_row  nunique_row   count
    0   Apple   {12, 13}            2  [2, 1]
    1   Lemon       {14}            1     [1]
    2  Orange   {13, 14}            2  [1, 1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-03
      • 2018-09-06
      • 2019-02-25
      • 2019-01-18
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2018-11-20
      相关资源
      最近更新 更多