Pandas Pivot Error “Exception: Data must be 1-dime

2019-08-02 00:12发布

I am using Pycharm (version 2018.2.4) with Python 3.6.7 running on it.

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

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

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?

Thanks!

3条回答
We Are One
2楼-- · 2019-08-02 00:52

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 )

Hope this helps!

查看更多
手持菜刀,她持情操
3楼-- · 2019-08-02 00:52

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

查看更多
The star\"
4楼-- · 2019-08-02 01:04

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
查看更多
登录 后发表回答