根据其他列划分列的值

时间:2017-11-15 17:41:33

标签: python pandas dataframe grouping

我有一个pandas数据框,如下所示:

index     ID           Val

 1    BBID_2041         1
 2    BBID_2041         1
 3    BBID_2041         3
 4    BBID_2041         1 
 5    BBID_2041         2
 6    BBID_2041         1
 7    BBID_2041         1
 8    BBID_20410        1
 9    BBID_20410        1
 10   BBID_20410        5
 11   BBID_20410        1

现在我想将列Val中的每个值除以该组中存在的ID总数。例如,我想将索引1到7的值除以7,因为ID BBID_2041总共有7行,依此类推。我可以使用循环,但这可能是一个快速的方法。

1 个答案:

答案 0 :(得分:2)

使用transform

df['New']=df.groupby('ID').Val.transform(lambda x : x/len(x))
df
Out[814]: 
    index          ID  Val       New
0       1   BBID_2041    1  0.142857
1       2   BBID_2041    1  0.142857
2       3   BBID_2041    3  0.428571
3       4   BBID_2041    1  0.142857
4       5   BBID_2041    2  0.285714
5       6   BBID_2041    1  0.142857
6       7   BBID_2041    1  0.142857
7       8  BBID_20410    1  0.250000
8       9  BBID_20410    1  0.250000
9      10  BBID_20410    5  1.250000
10     11  BBID_20410    1  0.250000
相关问题