2015-03-25 142 views
0

我有一個表「A」是這樣的:Python的大熊貓:分裂和追加?

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?

回答

0

一種方法是將一個函數應用到您的DF分裂「抄送」欄,並創建包含每個分裂國家及其相關計數一個新的字典,然後你可以從這個構造一個新的DF,GROUPBY國家和對數進行總和:

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 1265