每个ID多行数据
ID Value1 Value2
1 1 0
1 0 1
1 3 1期望输出
对于每个ID,SUM(Value1)-SUM(Value2)。
在这种情况下,对于ID1来说是4-2=2。
我想把结果放回原表,如下所示
ID Value1 Value2 Calculated_Value
1 1 0 2
1 0 1 2
1 3 1 2我试过this..it ran,但是输出表中有NaN。
df['Calculated_Value']= df.groupby(['ID'])['Value1'].sum()-df.groupby(['ID'])['Value2'].sum()发布于 2018-03-28 16:57:37
groupby操作的结果以及groupby操作之间的差异是由石斑鱼列定义索引的pd.Series,在本例中是ID。
因此,使用pd.Series.map和ID来提取groupwise结果。
df['Calculated_Value'] = df['ID'].map(df.groupby('ID')['Value1'].sum() - \
df.groupby('ID')['Value2'].sum())发布于 2018-03-28 16:59:00
您需要在这两个框架之间有类似的索引,当您在第二个组中groupby时,您将索引创建为ID
# Set the index first
df.set_index('ID', inplace=True)
# Now when we calculate, we can 'left join' onto the correct index values
df['Calculated_Value'] = df.groupby(['ID'])['Value1'].sum()-df.groupby(['ID'])['Value2'].sum()https://stackoverflow.com/questions/49540198
复制相似问题