如何解决分组依据和value_counts-将结果作为列返回
我有以下DF:
value name
A Steven
A Steven
A Ron
B Joe
B Steven
B Ana
我想对name列执行value_counts()操作,因此输出将是DF,其中这些列是值的计数器:
value Steven Ron Joe Ana
A 2 1 0 0
B 1 0 1 1
尝试按+ value_counts组,然后转置结果,但未达到输出。
解决方法
是<div style="margin-left: auto; margin-right: 20px;">
<svg>
<g transform="translate(20,20)">
<g class="legendCells"><g class="cell" transform="translate(0,5)">
<line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="2" style="fill: rgb(153,216,201);"></line>
<text class="label" transform="translate( 0,15)" style="text-anchor: start;">0.0</text></g><g class="cell" transform="translate(50,5)">
<line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="4" style="fill: rgb(211,74,65);"></line>
<text class="label" transform="translate( 0,15)" style="text-anchor: start;">2.5</text>
</g>
<g class="cell" transform="translate(100,5)">
<line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="6" style="fill: rgb(255,0);"></line>
<text class="label" transform="translate( 0,15)" style="text-anchor: start;">5.0</text>
</g>
<g class="cell" transform="translate(150,5)">
<line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="8" style="fill: rgb(255,15)" style="text-anchor: start;">7.5</text>
</g>
<g class="cell" transform="translate(200,5)">
<line class="swatch" x1="0" x2="40" y1="0" y2="0" stroke-width="10" style="fill: rgb(255,15)" style="text-anchor: start;">10.0</text>
</g>
</g>
</g>
</svg>
</div>
crosstab
,
您可以使用groupby
和value_counts
来做到这一点:
df.groupby('value')['name'].value_counts().unstack(fill_value=0).reset_index()
输出:
name value Ana Joe Ron Steven
0 A 0 0 1 2
1 B 1 1 0 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。