2015-12-14 46 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']