我需要统计name列和industry列中每个值的出现情况。目标是得到每个行业每个名称的总和。我的数据如下:
industry name
Home Mike
Home Mike,Angela,Elliot
Fashion Angela,Elliot
Fashion Angela,Elliot期望的输出是:
Home Mike:2 Angela:1 Elliot:1
Fashion Angela:2 Elliot:2发布于 2020-08-17 18:46:42
将它从注释中移开,调试并证明是有效的:
# count() in the next line won't work without an extra column
df['name_list'] = df['name'].str.split(',')
df.explode('name_list').groupby(['industry', 'name_list']).count()结果:
name
industry name_list
Fashion Angela 2
Elliot 2
Home Angela 1
Elliot 1
Mike 2发布于 2020-08-17 18:48:46
您可以使用collections.Counter返回一系列字典,如下所示:
from collections import Counter
s = df.name.str.split(',').groupby(df.industry).sum().agg(Counter)
Out[506]:
industry
Fashion {'Angela': 2, 'Elliot': 2}
Home {'Mike': 2, 'Angela': 1, 'Elliot': 1}
Name: name, dtype: object注意事项:每个单元格都是一个Counter对象。Counter是字典的子类,因此您可以将字典操作作为字典应用于它。
https://stackoverflow.com/questions/63456715
复制相似问题