熊猫从CSV生成多个xlsx文件

时间:2018-10-25 01:46:01

标签: python pandas

我正在尝试从一个CSV文件中生成多个Excel文件,但是在生成了少数文件后出现以下错误:

UnicodeDecodeError:“ ascii”编解码器无法解码位置8的字节0xc3:序数不在范围(128)中

生成少量文件后出现错误,我不确定文件是否有特定问题或代码中的任何问题,请帮助

代码如下:

 #!/usr/bin/env python
# coding: utf-8


import pandas as pd
import pandas.io.formats.excel
pandas.io.formats.excel.header_style = None


class AdvertiserList(object):

    def __init__(self, input_file):

        self.input_file = input_file
        self.file_csv = None
        self.writer = None
        self.path = None

    def read_csv(self):
        file_csv = pd.read_csv(self.input_file)
        file_csv_br = file_csv[file_csv['Market'] == 'BR']
        file_csv = file_csv.drop(file_csv_br.index, axis=0)
        self.file_csv = file_csv

    def generate_multiple_file(self):
        df_by_market = self.file_csv.groupby('Market')
        self.path = "C://Adops-Git//Files//"
        for(market, market_df) in df_by_market:
            self.writer = pd.ExcelWriter(self.path + "{}.xlsx".format(market), engine="xlsxwriter")
            # file_name = self.writer
            market_df.to_excel(self.writer, index=False)
            self.writer.save()
            self.writer.close()

    def main(self):
        self.read_csv()
        self.generate_multiple_file()


if __name__ == "__main__":
    object_advertiser = AdvertiserList('C://Adops-Git//Files//Account_&_Advertisers_List_data.csv')
    object_advertiser.main()

1 个答案:

答案 0 :(得分:0)

只需尝试

market_df.to_excel(self.path + "{}.xlsx".format(market), index=False)

直接并使用默认的本地支持Unicode的xlsx编写器

如果没有编码参数选项,那么从注释中您可能正在使用过时的熊猫版本。

相关问题