Python ValueError:长度不匹配:在熊猫数据框中创建分层列时,预期轴有 0 个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43190773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:37:05  来源:igfitidea点击:

ValueError: Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe

pythonpython-3.xpandasdataframemulti-index

提问by Peaceful

I was going through the documentationabout the hierarchical indexing in Pandas. I tried testing the examples from it to create an empty dataframe with hierarchical indexing:

我正在阅读有关 Pandas 中分层索引的文档。我尝试测试它的示例以创建一个带有分层索引的空数据框:

In [5]: df = pd.DataFrame()

In [6]: df.columns = pd.MultiIndex(levels = [['first', 'second'], ['a', 'b']], labels = [[0, 0, 1, 1], [0, 1, 0, 1]])

However, it throws an error:

但是,它会引发错误:

ValueError                                Traceback (most recent call last)
<ipython-input-6-dd823f9b8d22> in <module>()
----> 1 df.columns = pd.MultiIndex(levels = [['first', 'second'], ['a', 'b']], labels = [[0, 0, 1, 1], [0, 1, 0, 1]])

/usr/local/lib/python3.4/dist-packages/pandas/core/generic.py in __setattr__(self, name, value)
   2755         try:
   2756             object.__getattribute__(self, name)
-> 2757             return object.__setattr__(self, name, value)
   2758         except AttributeError:
   2759             pass

pandas/src/properties.pyx in pandas.lib.AxisProperty.__set__ (pandas/lib.c:44873)()

/usr/local/lib/python3.4/dist-packages/pandas/core/generic.py in _set_axis(self, axis, labels)
    446 
    447     def _set_axis(self, axis, labels):
--> 448         self._data.set_axis(axis, labels)
    449         self._clear_item_cache()
    450 

/usr/local/lib/python3.4/dist-packages/pandas/core/internals.py in set_axis(self, axis, new_labels)
   2800             raise ValueError('Length mismatch: Expected axis has %d elements, '
   2801                              'new values have %d elements' %
-> 2802                              (old_len, new_len))
   2803 
   2804         self.axes[axis] = new_labels

ValueError: Length mismatch: Expected axis has 0 elements, new values have 4 elements

I don't see any problem with my code. Any ideas what is happening?

我的代码没有任何问题。任何想法发生了什么?

回答by Psidom

The problem is that you have an empty data frame which has zero columns, and you are trying to assign a four columns multi-index to it; If you create an empty data frame of four columns initially, the error will be gone:

问题是您有一个包含零列的空数据框,并且您试图为其分配一个四列多索引;如果最初创建一个四列的空数据框,错误将消失:

df = pd.DataFrame(pd.np.empty((0, 4)))    
df.columns = pd.MultiIndex(levels = [['first', 'second'], ['a', 'b']], labels = [[0, 0, 1, 1], [0, 1, 0, 1]])

Or you can create empty data frame with the multi-index as follows:

或者您可以使用多索引创建空数据框,如下所示:

multi_index = pd.MultiIndex(levels = [['first', 'second'], ['a', 'b']], labels = [[0, 0, 1, 1], [0, 1, 0, 1]])    
df = pd.DataFrame(columns=multi_index)

df
#   first    second
#  a    b   a     b