Pandas Pivot错误“例外:数据必须为一维". [英] Pandas Pivot Error "Exception: Data must be 1-dimensional"
问题描述
我正在使用Pycharm(版本2018.2.4),并在其上运行Python 3.6.7.
I am using Pycharm (version 2018.2.4) with Python 3.6.7 running on it.
我目前尝试使用pandas枢纽功能,但甚至使用示例代码:
I currently try to use the pandas pivot function, but even the sample code:
import pandas as pd
df = pd.DataFrame({'foo':['one', 'one', 'one', 'two', 'two','two'],'bar':
['A', 'B', 'C', 'A', 'B', 'C'],'baz': [1, 2, 3, 4, 5, 6],'zoo': ['x',
'y', 'z', 'q', 'w', 't']})
df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
导致错误: 例外:数据必须是一维的
只有当我将一列列传递给values参数时,这种情况才会出现,但是该示例直接来自函数帮助: https://pandas.pydata.org/pandas- docs/stable/generated/pandas.DataFrame.pivot.html
This is only the case when I pass a list of columns to the values parameter, however this example is taken straight from the function help: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html
它过去曾经为我工作,但本周已停止工作,不知道为什么.我的熊猫版本是0.23.4,numpy版本是1.15.4.
It used to work for me in the past and has stopped working this week, not sure why. My pandas version is 0.23.4 and numpy version is 1.15.4.
有人知道导致此问题/如何解决此问题的原因吗?
Does anybody know what is causing this/how to fix it?
谢谢!
推荐答案
在jupyter笔记本中进行测试时,我能够重新创建相同的错误, 熊猫:0.22.0和numpy:1.14.0.
I was able to recreate the same error when testing in jupyter notebook with pandas: 0.22.0 and numpy: 1.14.0.
我无法弄清楚为什么会发生此问题,但我将示例中的代码重写为
I wasn't able to figure out why this issue happens but I rewrote the code in the example as
import pandas as pd
df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
'two'],
'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
'baz': [1, 2, 3, 4, 5, 6],
'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
df.set_index(['foo','bar'],inplace=True)
df.unstack(level=1)
并获得了预期的输出(如熊猫文档)
and got the expected output (as seen in the pandas doc )
希望这会有所帮助!
这篇关于Pandas Pivot错误“例外:数据必须为一维".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!