[英]sum of value occurrence grouped by another column pandas df
我需要按列industry
統計列name
和分組中每個值的出現次數。 目標是獲得每個行業的每個名稱的總和。 我的數據如下所示:
industry name
Home Mike
Home Mike,Angela,Elliot
Fashion Angela,Elliot
Fashion Angela,Elliot
所需的 output 是:
Home Mike:2 Angela:1 Elliot:1
Fashion Angela:2 Elliot:2
將其從評論中移出,經過調試並證明有效:
# 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
您可以使用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
object。 Counter
是字典的子類,因此您可以在其上應用字典操作作為字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.