首页 > 解决方案 > AttributeError:“索引”对象没有属性“to_excel”

问题描述

类似的问题还有很多。这里有两个:

Python 错误:AttributeError:“NoneType”对象没有属性“to_excel”

AttributeError: '对象没有属性'

我想用 excel 文件列标题中的空格替换下划线,然后保存。这是代码:

import pandas as pd

ws = r'c:/users/jpilbeam/Reverse911_1a_English_.xlsx'

# data frame from excel file 
df3 = pd.read_excel(ws, header=0) 
#remove underscores
df2 = df3.columns.str.replace("_", " ")
## save to file
df2.to_excel(df2)

这是完整的错误:

Traceback (most recent call last):
  File "\\pathto\Python Scripts\C19VaccinationTable.py", line 18, in <module>
    df2.to_excel(df2)
AttributeError: 'Index' object has no attribute 'to_excel'

在调试时,我注意到脚本将columns.str.replace()成功打印该函数。但是,它不会写入 excel 文件。

标签: pythonexcelpandas

解决方案


df3.columns是一个索引对象 ( pandas.Index),因此当您替换_它时,它会返回一个索引对象。而是这样做:

import pandas as pd

ws = r'c:/users/jpilbeam/Reverse911_1a_English_.xlsx'

# data frame from excel file 
df3 = pd.read_excel(ws, header=0) 
#remove underscores
df3.columns = df3.columns.str.replace("_", " ")
## save to file
df3.to_excel(filename)   # filename being the file name you want to save it in.

要查看它是如何工作的,您可以跟踪每个步骤:

>>> df = pd.DataFrame(np.random.randint(1,10, (3,4)), columns=['a_', 'b_', 'c_', 'd_'])
>>> df
 
   a_  b_  c_  d_
0   7   3   6   7
1   2   4   7   8
2   5   8   2   9

>>> df.columns  # pd.Index object
Index(['a_', 'b_', 'c_', 'd_'], dtype='object')

>>> df2 = df.columns.str.replace('_', '')

>>> df2   # Again, pd.Index object, not DataFrame
Index(['a', 'b', 'c', 'd'], dtype='object')

# But if we assign it back to df.columns:
>>> df.columns = df.columns.str.replace('_', '')

>>> df
 
   a  b  c  d
0  7  3  6  7
1  2  4  7  8
2  5  8  2  9

推荐阅读