我有一个数据集 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
正在做
df2 = pd.DataFrame()
df2['sku'] = df.groupby('location')['sku'].nth(0)
df2['count'] = df.groupby('sku').count()
但是,我得到了 NAN 进行计数,但没有得到 sku 下列出的所有数据。
如有任何建议,我们将不胜感激。
最佳答案
您希望按两列进行分组:
df.groupby(['location','sku']).size().reset_index(name='count')
或者按一列和 value_counts
另一列进行分组:
# 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
关于python - 按一列分组并计算 Pandas 中的多个类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66593073/