【问题标题】:pandas dataframe to csv export issue熊猫数据框到 csv 导出问题
【发布时间】:2018-10-25 19:32:46
【问题描述】:

得到一个奇怪的错误,在 jupyter 笔记中我可以运行:

df1.to_csv("{0}{1}.csv".format(report_path,db))  

我的 csv 出来了。

当我尝试在 jupyter 之外执行相同的操作时,将上述内容放入外部文件中并运行:

    #imports requred to run querys
    import pandas as pd
    from pandas import DataFrame,Series
    import numpy as np
    from pyhive import presto
    import matplotlib.pyplot as plt
    import seaborn as sn    

 #run config file, which contains the query to generate the report
    def run_config(db):
        print args.an
        print ("config is = {0}".format(config))
        with open(config) as cfg:
            v = cfg.read()
        exec v

我收到此错误:

lib.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer)
File "pandas/_libs/lib.pyx", line 1035, in pandas._libs.lib.write_csv_rows
UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-11: ordinal not in range(128)

我相当确定它在我的 DF 中导致了这个错误,因为其他 df 没有这个问题。但是我迷失了如何修复或编辑代码来捕获它。

修复

df1.to_csv("{0}{1}.csv".format(report_path,db), encoding='utf8-8')

【问题讨论】:

    标签: python python-2.7 pandas jupyter-notebook exec


    【解决方案1】:

    我会尝试将代码更改为

    df1.to_csv("{0}{1}.csv".format(report_path,db), encoding='utf8-8')
    
    1. 您遇到的字符不是 ASCII 很明显
    2. 我的猜测是您的 Jupyter 运行的解释器与您的脚本不同
    3. 对于非 ASCII 编码,UTF8 是一个不错的首选;如果它不起作用,请查看Unicode, Dammit

    【讨论】:

    • 这是一个很好的猜测,我认为是正确的。我什至不知道您可以向 to_csv 函数添加编码选项,谢谢
    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多