在pandas中按索引+列分组

vum*_*sha 33 python pandas

我有一个包含列的数据框

  1. 用户身份
  2. item_bought

这里user_id是df的索引.我想通过user_id和item_bought进行分组,并为用户获取项目明智的计数.我怎么做.

谢谢

kek*_*ert 33

这应该工作:

>>> df = pd.DataFrame(np.random.randint(0,5,(6, 2)), columns=['col1','col2'])
>>> df['ind1'] = list('AAABCC')
>>> df['ind2'] = range(6)
>>> df.set_index(['ind1','ind2'], inplace=True)
>>> df

           col1  col2
ind1 ind2            
A    0        3     2
     1        2     0
     2        2     3
B    3        2     4
C    4        3     1
     5        0     0


>>> df.groupby([df.index.get_level_values(0),'col1']).count()

           col2
ind1 col1      
A    2        2
     3        1
B    2        1
C    0        1
     3        1
Run Code Online (Sandbox Code Playgroud)

我使用multiindex中的一个列时遇到了同样的问题.使用multiindex,你不能使用df.index.levels [0],因为它只有特定索引级别的不同值,并且很可能与整个数据帧的大小不同...

检查http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html - get_level_values"返回请求级别的标签值向量,等于索引的长度"


jez*_*ael 33

从版本0.20.1开始,它更简单:

传递给DataFrame.groupby()的字符串作为by参数现在可以引用列名称或索引级别名称

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]

index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])

df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 3, 3],
                   'B': np.arange(8)}, index=index)

print (df)

              A  B
first second      
bar   one     1  0
      two     1  1
baz   one     1  2
      two     1  3
foo   one     2  4
      two     2  5
qux   one     3  6
      two     3  7

print (df.groupby(['second', 'A']).sum())
          B
second A   
one    1  2
       2  4
       3  6
two    1  4
       2  5
       3  7
Run Code Online (Sandbox Code Playgroud)


how*_*ese 4

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
Run Code Online (Sandbox Code Playgroud)