lovelygood183
2021-09-04 21:43
采纳率: 50%
浏览 46
已结题

pandas中先判断表头为空后自定义表头

import pandas as pd
people=pd.read_excel('D:/myPython/people.xlsx',header=None)#表头为空
people.columns=['ID','TypeName','irstName','MiddleName','LastName']#定义表头
people.set_index("ID",inplace=True)#设置ID为索引
print(people.columns)
people.to_excel('D:/myPython/output.xlsx')
print('Done!')

请教各位,我按着学习教程来写的代码,目的:
提取people中的字段,判断表头为空后,定义表头,并将ID设置为索引;
最后将数据另存于output表格中,运行后报错,请各位指点下哪错了,谢谢~

--------------------报错提示------------------------------------------------------------------------------------------------
Traceback (most recent call last):
File "D:/myPython/Pandas/读取文件.py", line 15, in
people.columns=['ID','TypeName','irstName','MiddleName','LastName']#定义表头
File "C:\Users\hw\anaconda3\lib\site-packages\pandas\core\generic.py", line 5152, in setattr
return object.setattr(self, name, value)
File "pandas_libs\properties.pyx", line 66, in pandas._libs.properties.AxisProperty.set
File "C:\Users\hw\anaconda3\lib\site-packages\pandas\core\generic.py", line 564, in _set_axis
self._mgr.set_axis(axis, labels)
File "C:\Users\hw\anaconda3\lib\site-packages\pandas\core\internals\managers.py", line 226, in set_axis
raise ValueError(
ValueError: Length mismatch: Expected axis has 6 elements, new values have 5 elements

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 已采纳

    值错误:长度不匹配:期望轴有6个元素,新值有5个元素

    评论
    解决 1 无用
    打赏 举报

相关推荐 更多相似问题