我们有以下具有3列的数据帧(df)。目标是确保"加载"的总和。对于基于ID的每个组,等于1.
pd.DataFrame({'ID':['AEC','AEC','CIZ','CIZ','CIZ'],'Load':[0.2093275,0.5384086,0.1465657,0.7465657,0.1465657]})
Num ID Load
1 AEC 0.2093275
2 AEC 0.5384086
3 CIZ 0.1465657
4 CIZ 0.7465657
5 CIZ 0.1465657
如果组的总负载小于或大于1,我们只想添加或减去该组的一个成员,使总和等于1而不添加额外的行数据帧(只需修改值)。我们怎么能这样做?
提前谢谢大家。
答案 0 :(得分:2)
您可以使用drop_duplicates保留每个组中的第一条记录,然后更改Load值,使其Load load sum为1。
df.loc[df.ID.drop_duplicates().index, 'Load'] -= df.groupby('ID').Load.sum().subtract(1).values
df
Out[92]:
Num ID Load
0 1 AEC 0.461591
1 2 AEC 0.538409
2 3 CIZ 0.106869
3 4 CIZ 0.746566
4 5 CIZ 0.146566
df.groupby('ID').Load.sum()
Out[93]:
ID
AEC 1.0
CIZ 1.0
Name: Load, dtype: float64
答案 1 :(得分:1)
我正在使用重新采样从每个组中随机选择一个值来进行更改
df['New']=(1-df.groupby('ID').Load.transform('sum'))
df['Load']=df.Load.add(df.groupby('ID').New.apply(lambda x : x.sample(1)).reset_index('ID',drop=True)).fillna(df.Load)
df.drop('New',1)
Out[163]:
Num ID Load
0 1 AEC 0.209327
1 2 AEC 0.790673
2 3 CIZ 0.146566
3 4 CIZ 0.746566
4 5 CIZ 0.106869
检查
df.drop('New',1).groupby('ID').Load.sum()
Out[164]:
ID
AEC 1.0
CIZ 1.0
Name: Load, dtype: float64