【问题标题】:output the count of the items as header pandas将项目的数量输出为 header pandas
【发布时间】:2020-05-22 18:38:40
【问题描述】:

这是我的数据框: '''

 customer product     product1
0        A    hats        shoes
1        A   socks        shoes
2        B   socks        shoes
3        C    hats        shoes
4        C    None  accessories
5        B   socks        shoes
6        A    hats        shoes
7        C    None  accessories

''' 我想输出这样的东西:

customer    shoes   hats    socks   accessories
A             #       #        #    #
B             #       #        #    #
C             #       #        #    #

我尝试过这样的 group by: '''

dfB.set_index('customer').groupby(['product', 'product1']).agg({'product':['count'], 'product1':['count']}) '''

我得到这样的输出:

'''

 product product1
                   count    count
product product1                 
 hats   shoes          3        3
 socks  shoes          3        3

'''

请帮忙

【问题讨论】:

    标签: python-3.x pandas pandas-groupby


    【解决方案1】:

    IIUC

    我们可以将索引设置为“客户”,然后堆叠数据框,让您可以使用 value_counts 进行聚合

    df2 = df.set_index('customer').stack().groupby(level=0).value_counts().unstack()
    

    -

    print(df2)
              None  accessories  hats  shoes  socks
    customer                                       
    A          NaN          NaN   2.0    3.0    1.0
    B          NaN          NaN   NaN    2.0    2.0
    C          2.0          2.0   1.0    1.0    NaN
    

    如果您不关心None,您可以将其转换为真正的空值,它将在groupby 中被忽略

    print(df.replace('None',np.nan).set_index('customer').stack().groupby(level=0).value_counts().unstack())
    
              accessories  hats  shoes  socks
    customer                                 
    A                 NaN   2.0    3.0    1.0
    B                 NaN   NaN    2.0    2.0
    C                 2.0   1.0    1.0    NaN
    

    【讨论】:

      【解决方案2】:

      你可以melt 然后pivot_table

      # df = df.replace('None', None) # If `'None'` and not `None`
      
      (df.melt('customer', value_name='product')
         .pivot_table(index='customer', columns='product', aggfunc='size'))
      
      product   accessories  hats  shoes  socks
      customer                                 
      A                 NaN   2.0    3.0    1.0
      B                 NaN   NaN    2.0    2.0
      C                 2.0   3.0    1.0    NaN
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-16
        • 2018-04-18
        • 1970-01-01
        • 2019-03-31
        • 1970-01-01
        相关资源
        最近更新 更多