我想通过Column和groupby索引计算yes和no值的数量.
我有这个数据帧
:
col0 col1 col2
A yes no
A no no
B yes yes
B yes no
我要这个:
col1 col2
yes no yes no
A 1 1 0 2
B 2 0 1 1
我尝试使用df.pivot_table(index =’my_index’,aggfunc =’count’)
但我只有
col1 col2
A 2 2
B 2 2
解决方法:
选项1
pd.get_dummies groupby sum
v = pd.get_dummies(df.set_index('col0'))
v.columns = pd.MultiIndex.from_tuples(
list(map(tuple, v.columns.str.split('_')))
)
v.sum(level=0)
col1 col2
no yes no yes
col0
A 1 1 2 0
B 0 2 1 1
选项2
堆栈get_dummies unstack
(df.set_index('col0')
.stack()
.str.get_dummies()
.sum(level=[0,1])
.unstack(-1)
.swaplevel(0, 1, axis=1)
.sort_index(level=0, axis=1)
)
col1 col2
no yes no yes
col0
A 1 1 2 0
B 0 2 1 1
选项3
@Wen的交叉链接
i = pd.crosstab(df.col0, df.col1.astype('category'))
j = pd.crosstab(df.col0, df.col2.astype('category'))
pd.concat([i, j], axis=1, keys=['col1','col2'])
col1 col2
col1 no yes no yes
col0
A 1 1 2 0
B 0 2 1 1
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。