Python 基于其他列划分列的值

Python 基于其他列划分列的值,python,pandas,dataframe,grouping,Python,Pandas,Dataframe,Grouping,我有一个熊猫数据框,如下所示: 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

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

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行,以此类推。我可以使用一个循环,但什么可以是一个快速的方式做到这一点

使用
变换

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

通过使用
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