[英]Groupby in Pandas not working
数据每个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
我已经试过了..它运行了,但是输出表中出现了NaN。
df['Calculated_Value']= df.groupby(['ID'])['Value1'].sum()-df.groupby(['ID'])['Value2'].sum()
的结果groupby
操作,和之间的差异groupby
操作,是pd.Series
与索引由石斑鱼柱(一个或多个)中所定义,在此情况下ID
。
因此,使用带有ID
pd.Series.map
提取分组结果。
df['Calculated_Value'] = df['ID'].map(df.groupby('ID')['Value1'].sum() - \
df.groupby('ID')['Value2'].sum())
您需要在两个框架之间具有相似的索引,在第二组中进行分组时,您将索引创建为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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.