您可以将^{}与聚合sum聚合并通过^{}进行整形,最后用^{}替换缺失类别的nan:df = df.groupby(['name','condition'], sort=False)['data1'].sum().unstack()
df['total'] = df['a'].fillna(df['b'])
print (df)
condition a b total
name
one 7.0 3.0 7.0
two NaN 48.0 48.0
three 39.0 13.0 39.0
对于新的DataFrame:
^{pr2}$
另一个使用apply的解决方案:def f(x):
if (x['condition'] == 'a').any():
return x.loc[x['condition'] == 'a', 'data1'].sum()
else:
return x.loc[x['condition'] == 'b', 'data1'].sum()
df1 = df.groupby('name', sort=False).apply(f).reset_index(name='total')
print (df1)
name total
0 one 7
1 two 48
2 three 39
更好的方法是创建一个用于聚集过滤数据帧的序列,然后^{},但是这个解决方案忽略了没有a或{}条件的所有name组:a = df.loc[df['condition'] == 'a'].groupby('name', sort=False)['data1'].sum()
b = df.loc[df['condition'] == 'b'].groupby('name', sort=False)['data1'].sum()
df = a.combine_first(b).reset_index(name='total')
print (df)
name total
0 one 7.0
1 three 39.0
2 two 48.0