您好希望得到一些帮助,我有两列数据框df
as;
Source ID
1 2
2 3
1 2
1 2
1 3
3 1
我的目的是对源进行分组,并根据分组的源将 ID 单元格除以总数,并将其附加到原始数据帧,以便新列看起来像这样;
Source ID ID_new
1 2 2/9
2 3 3/3
1 2 2/9
1 2 2/9
1 3 3/9
3 1 3/1
我已经做到了;
df.groupby('Source ID')['ID'].sum()
得到总计ID
但我不知道下一步该去哪里。
尝试这个:
In [79]: df.assign(ID_new=df.ID/df.groupby('Source').ID.transform('sum'))
Out[79]:
Source ID ID_new
0 1 2 0.222222
1 2 3 1.000000
2 1 2 0.222222
3 1 2 0.222222
4 1 3 0.333333
5 3 1 1.000000
如果您需要它作为新的执着的您可以按照 @jezrael 中建议的方式进行操作comment https://stackoverflow.com/questions/39387954/pandas-divide-row-value-by-aggregated-sum-with-a-condition-set-by-other-cell/39388025?noredirect=1#comment66102743_39388025:
In [81]: df['ID_new'] = df.ID/df.groupby('Source').ID.transform('sum')
In [82]: df
Out[82]:
Source ID ID_new
0 1 2 0.222222
1 2 3 1.000000
2 1 2 0.222222
3 1 2 0.222222
4 1 3 0.333333
5 3 1 1.000000
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)