简体   繁体   English

Pandas Pivot错误“例外:数据必须为一维”

[英]Pandas Pivot Error “Exception: Data must be 1-dimensional”

I am using Pycharm (version 2018.2.4) with Python 3.6.7 running on it. 我正在将Pycharm(2018.2.4版本)与运行于其上的Python 3.6.7一起使用。

I currently try to use the pandas pivot function, but even the sample code: 我目前尝试使用pandas枢纽函数,甚至使用示例代码:

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'])

leads to the error: Exception: Data must be 1-dimensional 导致错误: 异常:数据必须为一维

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 仅当我将一列列表传递给values参数时,才有这种情况,但是此示例直接来自函数帮助: https : //pandas.pydata.org/pandas-docs/stable/generation/pandas.DataFrame。 pivot.html

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. 我的熊猫版本是0.23.4,numpy版本是1.15.4。

Does anybody know what is causing this/how to fix it? 有人知道导致此问题/如何解决它的原因吗?

Thanks! 谢谢!

I was able to recreate the same error when testing in jupyter notebook with pandas: 0.22.0 and numpy: 1.14.0. 在Jupyter Notebook中使用Pandas:0.22.0和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 doc所示

Hope this helps! 希望这可以帮助!

The following works for me. 以下对我有用。 Give it a try! 试试看!

 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')[['baz', 'zoo']] 

If you make it a dictionary, it could work fine. 如果您将其制成字典,则可以正常使用。 Try this! 尝试这个!

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'])

#output:

    baz zoo
bar A   B   C   A   B   C
foo                     
one 1   2   3   x   y   z
two 4   5   6   q   w   t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM