Pandas 未在索引分配 Python3.5.0 后添加列

我尝试了以下陈述:


import pandas as pd

df = pd.DataFrame(index=[i for i in range(5)])

df.columns = ["res"+str(i) for i in range(5)]

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "C:\Python35\lib\site-packages\pandas\core\generic.py", line 5080, in __setattr__

    return object.__setattr__(self, name, value)

  File "pandas\_libs\properties.pyx", line 69, in pandas._libs.properties.AxisProperty.__set__

  File "C:\Python35\lib\site-packages\pandas\core\generic.py", line 638, in _set_axis

    self._data.set_axis(axis, labels)

  File "C:\Python35\lib\site-packages\pandas\core\internals\managers.py", line 155, in set_axis

    'values have {new} elements'.format(old=old_len, new=new_len))

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

不明白这是什么原因。如果我有索引,那么为什么没有添加该列?


桃花长相依
浏览 60回答 2
2回答

POPMUISE

我认为问题首先是没有创建列DataFrame,所以如果要分配列名它失败了。解决方案是将参数添加columns到 DataFrame 构造函数,索引应简化 - 仅分配range:df = pd.DataFrame(index= range(5), columns=["res"+str(i) for i in range(5)])print (df)&nbsp; res0 res1 res2 res3 res40&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN1&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN2&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN3&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN4&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN&nbsp; NaN如果想在只有索引的 DataFrame 之后分配,可以使用DataFrame.reindex:df = pd.DataFrame(index=range(5))df = df.reindex(["res"+str(i) for i in range(5)], axis=1)print (df)&nbsp; &nbsp;res0&nbsp; res1&nbsp; res2&nbsp; res3&nbsp; res40&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN1&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN2&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN3&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN4&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN&nbsp; &nbsp;NaN

LEATH

import pandas as pddf = pd.DataFrame(index= range(5))for i in range(5):&nbsp; df['res'+str(i)]= '0'print (df)&nbsp; res0 res1 res2 res3 res40&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 01&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 02&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 03&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 04&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0&nbsp; &nbsp; 0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python