将熊猫数据框保存到zip文件中的csv中

时间:2019-01-22 10:21:50

标签: python pandas dataframe zip

我正在尝试将熊猫的数据框保存到zip存档中的CSV文件中。我查阅了pandas文档,似乎支持zip压缩,但是它不能按预期工作。下面的代码保存一个zip文件

df_test.to_csv(path_filtered_zips + '{}.zip'.format(name_of_the_file), compression='zip', index=False)

压缩文件内部是从我的分区到压缩文件本身的路径。请参见下面的图片:

enter image description here

如果我将文件类型更改为“ .gz”,并将压缩类型更改为gzip,则设法将其正确保存。这将创建gz归档文件,并在文档中创建没有实际可打开格式的文件,这是我期望的数据框。您可以在这里看到

enter image description here 问题是我需要将归档文件压缩/压缩,并将其中的文件设置为CSV文件格式,因为我打算将其用于其他目的。

我用来产生这些结果的代码如下:

for zip_file in list_of_zip_file:
    counter += 1
    full_name = zip_file.split(".")
    name_of_the_file = full_name[0]
    archive = zipfile.ZipFile(path_zip_files + '/' + zip_file, "r")
    column_names = ['ip', 'date', 'cik', 'accession']
    df_test = pd.read_csv(archive.open(str(name_of_the_file) + ".csv"), low_memory=False, usecols=column_names)
    df_test = pd.merge(df_test, df_form, how='inner', on=['accession'])

    # The next line is where I changed the ".gz" and the compression to "zip" and get the mentioned errors. 
    df_test.to_csv(path_filtered_zips + '{}.gz'.format(name_of_the_file), compression='gzip', index=False)
    print(df_test)
    if counter == 1:
        break

0 个答案:

没有答案