【问题标题】:Pandas to_csv saving as NoneType and raising TypeErrorPandas to_csv 保存为 NoneType 并引发 TypeError
【发布时间】:2021-03-01 19:35:48
【问题描述】:

我正在尝试创建一个上传工具,该工具采用 .xls 文件,然后将其转换为 pandas 数据帧,最后将其保存为 csv 文件以进行处理和分析。文件出来后这段代码:

def xls_to_csv(data):
    #Formats into pandas dataframe. Index removes first column of .xls file.
    formatted_file = pd.read_excel(data, index_col=0)
    #Converts the formatted file into a csv file and saves it.
    final_file = formatted_file.to_csv('out.csv')

它正确保存在正确的位置,但是当我尝试将结果文件插入包含循环的其他函数时,它会引发

TypeError: 'NoneType' 对象不可迭代。

该文件保存为“out.csv”,我可以手动打开它,但是如果没有引发此错误,打开命令甚至无法工作。

我使用的是 Python 3.6。

【问题讨论】:

  • to_csv() 将数据帧写入文件并且不返回任何内容。 final_file 永远是 NoneType。另外,您能显示实际导致错误的代码或代码行吗?

标签: python python-3.x pandas


【解决方案1】:

to_csv 返回None 这就是你得到那个错误的原因 维护formatted_file,你可以试试这个,

final_file=formatted_file.copy()

final_file=pd.read_csv('out.csv')

【讨论】:

  • 所有错误均指我尝试在 Python 脚本中实现 csv 文件的行。
【解决方案2】:

Pandas to_csv 函数保存文件但不返回任何内容。稍后要循环遍历 csv 文件,您必须将代码更改为如下所示。

formatted_file.to_csv('out.csv')
final_file = open('out.csv', 'r')

【讨论】:

    【解决方案3】:
    def xls_to_csv(data):
    
        # Read the excel file as a dataframe object
        formatted_dataframe = pd.read_excel(data, index_col=0)
    
        # Save the dataframe to a csv file in disk. The method returns None.
        formatted_file.to_csv('out.csv')
    
        # The dataframe object is still here
        final_dataframe = formatted_dataframe
    
        # The final file NAME
        final_filename = 'out.csv'
    

    您的变量名具有误导性

    • 您的formatted_file 实际上是一个数据框对象
    • 你的final_file:我不清楚你是想要filename还是the dataframe

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 2014-02-04
      • 2018-06-11
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多