Python Pandas Pivot - 为什么失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26765041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:37:53  来源:igfitidea点击:

Python Pandas Pivot - Why Fails

pythonpython-2.7pandas

提问by user1617979

I have tried for a while to get this to wrk and I can't - I read the documentation and I must be misunderstanding something

我已经尝试了一段时间来解决这个问题,但我不能 - 我阅读了文档,我一定是误解了一些东西

I have a Data Frame in long format and I want to make it wide - this is quite common. But I get an error

我有一个长格式的数据框,我想让它变宽 - 这很常见。但我收到一个错误

from pandas import DataFrame 
data = DataFrame({'value' : [1,2,3,4,5,6,7,8,9,10,11,12],
                  'group' : ['a','a','a','b','b','b','b','c','c','c','d','d']})
data.pivot(columns='group')

the error I get is (the lats part, as they are quite extensive): ValueError: cannot label index with a null key

我得到的错误是(lats 部分,因为它们非常广泛):ValueError: cannot label index with a null key

I tried this in python (notebook) and also on regular python c command line in OS X with the same result

我在 python (notebook) 和 OS X 中的常规 python c 命令行中尝试过这个,结果相同

Thanks for any insight, I am sure it will be something basic

感谢您的任何见解,我相信这将是一些基本的东西

回答by Anzel

From what you were trying to do, you were trying to pass 'group' as indexso the pivot fails. It should be:

从您尝试做的事情来看,您试图通过“组”,index因此支点失败。它应该是:

data.pivot(data.index, 'group')

or,

或者,

# the format is pivot(index=None, columns=None, values=None)
data.pivot(index=data.index, columns='group')

However I'm not entirely sure what expected output you want, if you just want shorter presentation, you can always use transpose:

但是我不完全确定你想要什么预期的输出,如果你只是想要更短的演示,你总是可以使用transpose

data.T

or, the best for presentation in your case, is groupby:

或者,在您的案例中最适合展示的是groupby

data.groupby('group').sum()
       value
group       
a          6
b         22
c         27
d         23