How to pivot_table with with duplicated index

我的未来我决定 提交于 2019-12-11 17:13:41

问题


I have a df_ like this,

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

I am trying to create a pivot table with index='level',columns='status', values=sum of occurances with respect to the column and index

my code:

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

but gives me, ValueError: Index contains duplicate entries, cannot reshape

My expected output is,

      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.


回答1:


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)


来源:https://stackoverflow.com/questions/51420557/how-to-pivot-table-with-with-duplicated-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!