简体   繁体   中英

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.

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!

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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