擅长:python、mysql、java
<p>您需要<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer">^{<cd1>}</a>,因为<a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer">^{<cd2>}</a>分别处理每一列,所以<code>KeyError</code>:</p>
<pre><code>def f(x):
a = x['trade_shares'].sum()
b = x['total_value'].sum()
c = len(x)
#x['perf'] = x['IS/Order Start PTA - Realized Cost/Sh'] * x['trade_shares'] * 10000 / x['IS/Order Start PTA - Base Bench Price'] * x['trade_shares']
#x['net perf'] = x['IS/Order Start PTA - Realized Net Cost/Sh'] * x['trade_shares'] * 10000 / x['IS/Order Start PTA - Base Bench Price'] * x['trade_shares']
return pd.Series([a,b,c], index=['trade_shares','total_value','count'])
df = df.groupby(['region_2', 'trade_flag', 'broker']).apply(f).reset_index()
</code></pre>