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

时间:2019-02-20 22:24:38

标签: pandas

这与this question基本上是相同的问题。原始线程中的一种替代解决方案(set_index和unstack)适用,但是让我感到恐惧的是,这种基本功能在Pandas中不稳定。

我正在将Jupyter笔记本服务器5.0.0与Python 3.6.3 | Anaconda自定义(64位)一起使用。当我尝试运行此基本示例时:

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

我收到此错误“异常:数据必须为一维”。有人可以帮忙吗?

---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-14-3d9bf8b95839> in <module>()
      1 import pandas as pd
      2 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']})
----> 3 df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
      4 # df.set_index(['foo','bar'],inplace=True)
      5 # df=df.unstack(level=1)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in pivot(self, index, columns, values)
   3851         """
   3852         from pandas.core.reshape.reshape import pivot
-> 3853         return pivot(self, index=index, columns=columns, values=values)
   3854 
   3855     def stack(self, level=-1, dropna=True):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\reshape\reshape.py in pivot(self, index, columns, values)
    375             index = self[index]
    376         indexed = Series(self[values].values,
--> 377                          index=MultiIndex.from_arrays([index, self[columns]]))
    378         return indexed.unstack(columns)
    379 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    246             else:
    247                 data = _sanitize_array(data, index, dtype, copy,
--> 248                                        raise_cast_failure=True)
    249 
    250                 data = SingleBlockManager(data, index, fastpath=True)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in _sanitize_array(data, index, dtype, copy, raise_cast_failure)
   3025     elif subarr.ndim > 1:
   3026         if isinstance(data, np.ndarray):
-> 3027             raise Exception('Data must be 1-dimensional')
   3028         else:
   3029             subarr = _asarray_tuplesafe(data, dtype=dtype)

Exception: Data must be 1-dimensional

0 个答案:

没有答案