Python 按一列分组,并计算熊猫中的多个类别

Python 按一列分组,并计算熊猫中的多个类别,python,pandas,numpy,Python,Pandas,Numpy,我有一个数据集df,我想在其中按一列进行分组,然后在第二列中对每个类别进行计数 name location sku svc1 ny hey1 svc2 ny hey1 svc3 ny hey1 svc4 ny hey1 lo1 ny ok1 lo2 ny ok1 fab1 ny hi fab2 ny

我有一个数据集df,我想在其中按一列进行分组,然后在第二列中对每个类别进行计数

name    location    sku
svc1    ny          hey1
svc2    ny          hey1
svc3    ny          hey1
svc4    ny          hey1
lo1     ny          ok1
lo2     ny          ok1
fab1    ny          hi
fab2    ny          hi
fab3    ny          hi
hello   ca          no
hello   ca          no
渴望的

location    sku     count
ny          hey1    4
ny          ok1     2
ny          hi      3
ca          no      2
    

        

然而,我得到了NAN作为计数,并且我没有得到sku下列出的所有数据


任何建议都将不胜感激。

您希望通过两列进行分组:

df.groupby(['location','sku']).size().reset_index(name='count')
或按一列分组,并按值计数另一列:

# this should be slightly faster
(df.groupby('location')['sku'].value_counts()
      .reset_index(name='count'))
输出:

  location   sku  count
0       ca    no      2
1       ny  hey1      4
2       ny    hi      3
3       ny   ok1      2
  location   sku  count
0       ca    no      2
1       ny  hey1      4
2       ny    hi      3
3       ny   ok1      2