如何使用带有重复索引的数据透视表 [英] How to pivot_table with with duplicated index

查看:116
本文介绍了如何使用带有重复索引的数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的df _,

name  level  status
yes   high   open
no    high   closed
no    med    closed
yes   low    open
no    med    rejected
no    high   open

我正在尝试使用 index ='level',columns ='status',values =列和索引的出现次数之和创建一个数据透视表

我的代码:

df_['temp']=df_['level'].astype(bool).astype(int)
df_.pivot(index='level',columns='status',values='temp')

但是给我, ValueError:索引包含重复的条目,无法重塑

我的预期输出是

      open closed rejected
high  2    1      0
med   0    1      1
low   1    0      0

请检查并告诉我是否还有其他简单的方法。

Please check and tell me if there is any other easy way.

推荐答案

一种更简单的方法是计算名称的出现次数:

A simpler approach would be to count the occurrences of name:

df_.pivot_table(values='name',
                index='level',
                columns='status',
                aggfunc='count',
                fill_value=0)

这篇关于如何使用带有重复索引的数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆