【问题标题】:Count number of matching values from pandas groupby计算来自 pandas groupby 的匹配值的数量
【发布时间】:2020-06-06 18:25:37
【问题描述】:

我为商店创建了一个 pandas 数据框

我有 Transaction 和 Item_Type 列

import pandas as pd
data = {'Transaction':[1, 2, 2, 2, 3], 'Item_Type':['Food', 'Drink', 'Food', 'Drink', 'Food']}
df = pd.DataFrame(data, columns=['Transaction', 'Item_Type'])
Transaction Item_Type
1           Food
2           Drink
2           Food
2           Drink
3           Food

我正在尝试按交易分组并计算每笔交易的饮料数量,但找不到正确的语法。

df = df.groupby(['Transaction','Item_Type']).size()

这种工作,但给了我一个多索引系列,我还不知道如何从中选择每笔交易的饮料。

1/Food   1
2/Drink  2
2/Food   1
3/Food   1

这似乎很笨拙 - 有没有更好的方法?

这个 stackoverflow 看起来最相似 Adding a 'count' column to the result of a groupby in pandas?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    pivot_table 的另一种可能方式:

    s = df.pivot_table(index='Transaction',
                       columns='Item_Type',aggfunc=len).stack().astype(int)
    

    或者:

    s = df.pivot_table(index=['Transaction','Item_Type'],aggfunc=len) #@thanks @Ch3steR
    s.index = s.index.map("{0[0]}/{0[1]}".format)
    

    print(s)
    
    1/Food     1
    2/Drink    2
    2/Food     1
    3/Food     1
    

    或者,如果您希望过滤特定类别:

    to_filter = 'Drink'
    (df.pivot_table(index='Transaction',columns='Item_Type',aggfunc=len,fill_value=0)
                                                      .filter(items=[to_filter]))
    

     Item_Type    Drink
    Transaction       
    1                0
    2                2
    3                0
    ​
    

    【讨论】:

      【解决方案2】:

      编辑:在看到 anky 的答案后,用 unstack 替换原来的 xs 方法。

      >>> df.groupby('Transaction')['Item_Type'].value_counts().unstack(fill_value=0)['Drink']
      Transaction
      1    0
      2    2
      3    0
      Name: Drink, dtype: int64
      

      【讨论】:

        【解决方案3】:

        对于特定条件,您可以在检查条件后在组内sum布尔系列。

        df['Item_Type'].eq('Drink').groupby(df['Transaction']).sum()
        
        #Transaction
        #1    0.0
        #2    2.0
        #3    0.0
        #Name: Item_Type, dtype: float64
        

        【讨论】:

          【解决方案4】:

          我找到了我认为的解决方案

          Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

          df = df.groupby(['Transaction','Item_Type']).size().reset_index(name='counts')
          

          给我我需要的信息

          Transaction Item_Type counts
          1           Food      1
          2           Drink     2
          2           Food      1
          3           Food      1
          

          【讨论】:

            【解决方案5】:

            您可以使用aggvalue_counts

            s = df.astype(str).agg('/'.join, axis=1).value_counts(sort=False)
            
            Out[61]:
            3/Food     1
            2/Drink    2
            1/Food     1
            2/Food     1
            dtype: int64
            

            如果你想保持原来的顺序,链附加sort_index

            s = df.astype(str).agg('/'.join, axis=1).value_counts().sort_index(kind='mergesort')
            
            Out[62]:
            1/Food     1
            2/Drink    2
            2/Food     1
            3/Food     1
            dtype: int64
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-05-10
              • 2019-01-03
              • 2017-01-26
              • 2014-07-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多