我有一个'a‘表,就像这样:
count cc
68 IL-US
1 IL
12 US
5 US
1180 US-DE
4424 GB-ES-DE-A1-FR
0
20 DE
37 A1我希望得到每个国家/地区的计数总和,如下所示:
count cc
1265 US
69 IL
4424 GB
4424 ES
4424 FR
5624 DE
4461 A1我已经尝试过了,但这不能拆分,这只是对它们进行分组并对计数求和:
a.head(50).groupby(['cc']).aggregate(sum)['count']有人知道如何在ipython pandas中做到这一点吗?
发布于 2015-03-25 19:05:57
一种方法是对df应用一个函数来拆分'cc‘列,并创建一个包含每个拆分的国家及其相关计数的新字典,然后可以由此构造一个新的df,按国家分组,并对计数进行求和:
In [72]:
from collections import defaultdict
master = defaultdict(list)
def func(x):
if pd.isnull(x['cc']):
return
t = defaultdict(list)
for v in x['cc'].split('-'):
master['country'].append(v)
master['count'].append(x['count'])
df.apply(lambda x: func(x), axis=1)
df = pd.DataFrame(dict(master))
df
Out[72]:
count country
0 68 IL
1 68 US
2 1 IL
3 12 US
4 5 US
5 1180 US
6 1180 DE
7 4424 GB
8 4424 ES
9 4424 DE
10 4424 A1
11 4424 FR
12 20 DE
13 37 A1
In [73]:
df.groupby('country')['count'].sum()
Out[73]:
country
A1 4461
DE 5624
ES 4424
FR 4424
GB 4424
IL 69
US 1265
Name: count, dtype: int64如果希望国家/地区标识符以列的形式返回,可以调用reset_index
In [74]:
df.groupby('country')['count'].sum().reset_index()
Out[74]:
country count
0 A1 4461
1 DE 5624
2 ES 4424
3 FR 4424
4 GB 4424
5 IL 69
6 US 1265https://stackoverflow.com/questions/29253441
复制相似问题