Python - Pandas 在多个 Zip 文件中连接多个文本文件

标签 python pandas zip

我在使用 pandas 加载/连接压缩文件中的 txt 文件时遇到问题。这里有很多 pd.concat(zip_file.open) 的例子,但在我的例子中仍然没有任何效果,因为我有多个 zip 文件和多个 txt 文件。

例如,假设我在特定文件夹“Main”中有两个压缩文件。每个压缩文件都包含五个 txt 文件。我想阅读所有这些 txt 文件并将它们全部 pd.concat 在一起。在我的真实示例中,我将有几十个 zip 文件夹,每个文件夹包含五个 txt 文件。

你能帮忙吗?

文件夹和文件结构示例:

'C:/User/Example/Main'   
   TAG_001.zip
     sample001_1.txt
     sample001_2.txt
     sample001_3.txt
     sample001_4.txt
     sample001_5.txt
   TAG_002.zip
     sample002_1.txt
     sample002_2.txt
     sample002_3.txt
     sample002_4.txt
     sample002_5.txt

我是这样开始的,但之后的一切都抛出错误:

import os
import glob
import pandas as pd
import zipfile

path = 'C:/User/Example/Main'

ziplist = glob.glob(os.path.join(path, "*TAG*.zip"))

最佳答案

这不是很有效,但它应该让您了解如何完成。

import os
import zipfile

import pandas as pd

frames = {}

BASE_DIR = 'C:/User/Example/Main'
_, _, zip_filenames = list(os.walk(BASE_DIR))[0]
for zip_filename in zip_filenames:
    with zipfile.ZipFile(os.path.join(BASE_DIR, zip_filename)) as zip_:
        for filename in zip_.namelist():
            with zip_.open(filename) as file_:
                new_frame = pd.read_csv(file_, sep='\t')
                frame = frames.get(filename)
                if frame is not None:
                    pd.concat([frame, new_frame])
                else:
                    frames[filename] = new_frame

#once all frames have been concatenated loop over the dict and write them back out

根据有多少数据,您必须设计一个平衡处理能力/内存/磁盘空间的解决方案。此解决方案可能会耗尽大量内存。

关于Python - Pandas 在多个 Zip 文件中连接多个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52105556/

相关文章:

python - 根据 Pandas 中的外键减去多列

python-3.x - 根据列值从 Pandas Dataframe 中提取行

python - 如何使用 python(2.5 版)压缩文件夹的内容?

python - 如何提交仅给出 HTML 源的表单?

python - 导入错误:没有命名的模块

python - 如何连接到rabbitMQ docker容器?

c# - 提供下载链接而不在服务器上创建文件

python - 用于与 Python/Pandas 中的列中的先前值进行成对比较的循环

python - 使用 OneHotEncoder 拆分调查数据

c# - 如何压缩 FTP 服务器目录中的文件