您的位置: 网站首页> 大家问> 当前文章

IndexError: index 0 is out of bounds for axis 0 with size 0

老董2022-03-21193围观,143赞

  在用pandas时遇到了一个错误:IndexError: index 0 is out of bounds for axis 0 with size 0。看报错意思大概可以猜到是个空df引发的问题,因为报错提示index 0。具体是哪一步操作导致错误产生呢?

  经过反复测试,要产生这个报错需要具备3个条件:

  1、首先需要1个空df

  2、对空df设置二维索引

  3、把设置二维索引的空df写入excel会报错。

  我们用代码来演示一下:

# -*- coding:UTF-8 -*-
df = pd.DataFrame(columns=['name','age','hobby','higth'])
print(df)
df.set_index(['name','age'],inplace=True)
df.to_excel('aa.xlsx')
Empty DataFrame
Columns: [name, age, hobby, higth]
Index: []
Traceback (most recent call last):
  File "C:\Users\dong\Desktop\test\test.py", line 11, in <module>
    df.to_excel('aa.xlsx')
  File "D:\install\pyinstall\lib\site-packages\pandas\core\generic.py", line 2284, in to_excel
    formatter.write(
  File "D:\install\pyinstall\lib\site-packages\pandas\io\formats\excel.py", line 840, in write
    writer.write_cells(
  File "D:\install\pyinstall\lib\site-packages\pandas\io\excel\_xlsxwriter.py", line 227, in write_cells
    for cell in cells:
  File "D:\install\pyinstall\lib\site-packages\pandas\io\formats\excel.py", line 777, in get_formatted_cells
    for cell in itertools.chain(self._format_header(), self._format_body()):
  File "D:\install\pyinstall\lib\site-packages\pandas\io\formats\excel.py", line 596, in _format_header_regular
    coloffset = len(self.df.index[0])
  File "D:\install\pyinstall\lib\site-packages\pandas\core\indexes\multi.py", line 2042, in __getitem__
    if level_codes[key] == -1:
IndexError: index 0 is out of bounds for axis 0 with size 0

  如果不设置二维索引,一维索引的空df写入excel是没问题的,代码如下:

# -*- coding:UTF-8 -*-
df = pd.DataFrame(columns=['name','age','hobby','higth'])
print(df)
df.set_index(['name','age'],inplace=True)
print('ok')
Empty DataFrame
Columns: [name, age, hobby, higth]
Index: []
ok

  如果像系统的学习pandas实战教程,可以参考这个目录pandas教程

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    IndexError: index 0 is out of bounds for axis 0 with size 0文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200