Group by index + column in pandas

后端 未结 4 466
北荒
北荒 2021-02-02 05:27

I have a dataframe that has the columns

  1. user_id
  2. item_bought

Here user_id is the index of the df. I want to group by both user_id and item_b

4条回答
  •  情深已故
    2021-02-02 06:24

    import pandas as pd
    
    import numpy as np
    
    In [11]:
    
    df = pd.DataFrame()
    
    In [12]:
    
    df['user_id'] = ['b','b','b','c']
    
    In [13]:
    
    df['item_bought'] = ['x','x','y','y']
    
    In [14]:
    
    df['ct'] = 1
    
    In [15]:
    
    df
    
    Out[15]:
        user_id     item_bought     ct
    0   b   x   1
    1   b   x   1
    2   b   y   1
    3   c   y   1
    In [16]:
    
    pd.pivot_table(df,values='ct',index=['user_id','item_bought'],aggfunc=np.sum)
    
    Out[16]:
    
    user_id  item_bought
    b        x              2
             y              1
    c        y              1
    

提交回复
热议问题