【问题标题】:AttributeError: 'Index' object has no attribute 'to_excel'AttributeError:“索引”对象没有属性“to_excel”
【发布时间】:2021-01-29 20:26:28
【问题描述】:

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

Python Error: AttributeError: 'NoneType' object has no attribute 'to_excel'

AttributeError: 'Object has no attribute'

我想将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 文件。

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    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
    

    【讨论】:

    • df2 没有定义?
    • @Pfalbaum 添加了一些解释,我希望现在已经清楚了。您不需要定义 df2。
    • 我把你的代码一字不差,我得到的只是NameError: 'df2' is not defined 错误?
    • 对不起,这将是您的文件名。我会编辑它。我没注意到。
    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2021-12-31
    • 2017-03-05
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    相关资源
    最近更新 更多