<p>我最终决定使用apply。</p>
<p>我正在发布我的想法,希望它能对其他人有用。</p>
<p>根据我从韦斯的书《数据分析的Python》中了解到的情况</p>
<ul>
<li><strong>apply</strong>比agg和transform更灵活,因为您可以定义自己的函数。</li>
<li>唯一的要求是函数返回<em>pandas对象</em>或<em>标量值</em>。</li>
<li>内部机制:对每个分组对象调用函数,并使用<strong>pandas.concat将结果粘合在一起</li>
<li>一个需要“硬编码”结构,你想在最后</li>
</ul>
<p>这是我想到的</p>
<pre><code>def ZahlOccurence_0(x):
return pd.Series({'All': len(x['StudentID']),
'Part': sum(x['Participated'] == 'yes'),
'Pass' : sum(x['Passed'] == 'yes')})
</code></pre>
<p>当我运行它时:</p>
<pre><code> d1.groupby('ExamenYear').apply(ZahlOccurence_0)
</code></pre>
<p>我得到了正确的结果</p>
<pre><code> All Part Pass
ExamenYear
2007 3 2 2
2008 4 3 3
2009 3 3 2
</code></pre>
<p>这种方法还允许我将频率与其他统计数据结合起来</p>
<pre><code>import numpy as np
d1['testValue'] = np.random.randn(len(d1))
def ZahlOccurence_1(x):
return pd.Series({'All': len(x['StudentID']),
'Part': sum(x['Participated'] == 'yes'),
'Pass' : sum(x['Passed'] == 'yes'),
'test' : x['testValue'].mean()})
d1.groupby('ExamenYear').apply(ZahlOccurence_1)
All Part Pass test
ExamenYear
2007 3 2 2 0.358702
2008 4 3 3 1.004504
2009 3 3 2 0.521511
</code></pre>
<p>我希望其他人会觉得这个有用</p>