回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我的问题是如何计算熊猫体内多个变量的频率。
我从这个数据框得到:</p>
<pre><code>d1 = pd.DataFrame( {'StudentID': ["x1", "x10", "x2","x3", "x4", "x5", "x6", "x7", "x8", "x9"],
'StudentGender' : ['F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'],
'ExamenYear': ['2007','2007','2007','2008','2008','2008','2008','2009','2009','2009'],
'Exam': ['algebra', 'stats', 'bio', 'algebra', 'algebra', 'stats', 'stats', 'algebra', 'bio', 'bio'],
'Participated': ['no','yes','yes','yes','no','yes','yes','yes','yes','yes'],
'Passed': ['no','yes','yes','yes','no','yes','yes','yes','no','yes']},
columns = ['StudentID', 'StudentGender', 'ExamenYear', 'Exam', 'Participated', 'Passed'])
</code></pre>
<p>结果如下</p>
<pre><code> Participated OfWhichpassed
ExamenYear
2007 3 2
2008 4 3
2009 3 2
</code></pre>
<p>(1)我尝试的一种可能性是计算两个数据帧并绑定它们</p>
<pre><code>t1 = d1.pivot_table(values = 'StudentID', rows=['ExamenYear'], cols = ['Participated'], aggfunc = len)
t2 = d1.pivot_table(values = 'StudentID', rows=['ExamenYear'], cols = ['Passed'], aggfunc = len)
tx = pd.concat([t1, t2] , axis = 1)
Res1 = tx['yes']
</code></pre>
<p>(2)第二种可能性是使用聚合函数。</p>
<pre><code>import collections
dg = d1.groupby('ExamenYear')
Res2 = dg.agg({'Participated': len,'Passed': lambda x : collections.Counter(x == 'yes')[True]})
Res2.columns = ['Participated', 'OfWhichpassed']
</code></pre>
<p>至少可以说,这两种方式都很怪异。
<strong>熊猫是如何做到这一点的?</strong></p>
<p>p.S:我也尝试了<em>值计数</em>而不是<em>集合。Counter</em>但无法运行</p>
<p>供参考:几个月前,我向R<a href="https://stackoverflow.com/questions/11852408/">here</a>提出了类似的问题,<strong>plyr</strong>可能会有帮助</p>
<p><strong>----更新----</strong></p>
<p>用户<strong>DSM</strong>是对的。所需的表格结果中有一个错误。</p>
<p>(1)选项1的代码是</p>
<pre><code> t1 = d1.pivot_table(values = 'StudentID', rows=['ExamenYear'], aggfunc = len)
t2 = d1.pivot_table(values = 'StudentID', rows=['ExamenYear'], cols = ['Participated'], aggfunc = len)
t3 = d1.pivot_table(values = 'StudentID', rows=['ExamenYear'], cols = ['Passed'], aggfunc = len)
Res1 = pd.DataFrame( {'All': t1,
'OfWhichParticipated': t2['yes'],
'OfWhichPassed': t3['yes']})
</code></pre>
<p>它将产生结果</p>
<pre><code> All OfWhichParticipated OfWhichPassed
ExamenYear
2007 3 2 2
2008 4 3 3
2009 3 3 2
</code></pre>
<p>(2)对于选项2,由于用户<strong>herrfz</strong>,我找到了如何使用值计数的方法,代码将是</p>
<pre><code>Res2 = d1.groupby('ExamenYear').agg({'StudentID': len,
'Participated': lambda x: x.value_counts()['yes'],
'Passed': lambda x: x.value_counts()['yes']})
Res2.columns = ['All', 'OfWgichParticipated', 'OfWhichPassed']
</code></pre>
<p>将产生与Res1相同的结果</p>
<p>我的问题仍然是:</p>
<p>使用选项2,是否可以使用相同的变量两次(用于另一个操作?)是否可以为结果变量传递自定义名称?</p>
<p><strong>----新的更新----</strong></p>
<p>我终于决定使用<strong>apply</strong>我知道它更灵活。</p>