2015-12-14 23 views
0

如果有人能幫助我解決這個問題。我有兩個不同的小組。大熊貓在一張桌子上算作一個基於總數的頻率

df_base.groupby(['cdr3_len','Isotype'], as_index=False).sum() 

    cdr3_len Isotype count 
0   0  IgG 12148 
1   0  IgM 40918 
2   1  IgG  4723 
3   1  IgM 11107 
4   2  IgG  5633 
5   2  IgM 17684 
6   3  IgG 10332 
7   3  IgM 21621 
8   4  IgG  9301 
9   4  IgM 26348 
10   5  IgG 472232 
11   5  IgM 351317 
12   6  IgG 81520 
13   6  IgM 480543 
14   7  IgG 263317 
15   7  IgM 657392 

我希望計數作爲基於不同groupby語句的頻率出現。

df_new = df_base.groupby('Isotype',as_index=False).sum()[['Isotype','count']] 
IgG 20315380 
IgM 70268132 
Name: count, dtype: int64 

所以我想要一個新的列,稱爲頻率,將計數除以組的計數除以isotype。

因此,像

df_base['Frequency'] = df_base['count]/df_new[df_new['isotype'] == df_base['isotype']['count'] 

但顯然,這並不工作,因爲系列長度是不一樣的。任何想法

希望我有道理。

回答

1

嘗試合併GROUPBY DF對同型列,然後做一些在NEW_COLUMN = column_A/column_B

1

的格式,我認爲你正在尋找變換:

df_new = df_base.groupby(['cdr3_len','Isotype'], as_index=False).sum() 

# This creates an array of the same length as the original dataset. 
df_new['subtotal'] = df_new.groupby('Isotype')['count'].transform(sum) 

df_new['freq'] = df_new['count']/df_new['subtotal']