python - Pandas:将 WinZipped csv 文件转换为 Data Frame

标签 python pandas

我有几个 WinZipped csv 文件,想将它们作为 Pandas 数据框读取。问题是解压缩选项(“gzip”或“bz2”)似乎都不起作用。文件如下所示:

00000000011!00023011!89011!200812
00000000012!00023011!89011!200812
00000000013!00023011!89011!200812

所以看来我将不得不使用 Python 的 zipfile 模块解压缩文件,读入行并根据读入的内容创建一个数据框。我想这样做的方式是创建一个这样的字典列表:

[
    {"header1": 00000000011, "header2": 00023011, "header3": 89011, "header4": 200812}, 
    {"header1": 00000000012, "header2": 00023011, "header3": 89011, "header4": 200812},
    ...
]

然后将其转换为 http://pandas.pydata.org/pandas-docs/stable/dsintro.html#from-a-list-of-dicts 中的数据框.

但是,这似乎涉及大量手动操作线条 - 有没有更好的方法来做到这一点?

最佳答案

你只需要解压文件:

with zipfile.ZipFile('/path/to/file', 'r') as z:
    f = z.open('member.csv')
    table = pd.io.parsers.read_table(f, ...)

read_tablefilepath_or_buffer 参数接受任何类似文件的参数。

关于python - Pandas:将 WinZipped csv 文件转换为 Data Frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17789907/

相关文章:

Python Pandas : Search rows with consecutive condition

python - 按成对属性划分的 Pandas 切片

python 删除基于另一个列表的列表索引

python - 连接并填充 Pandas 中缺失的列

python - 国家 : Convert Country Names (Possibly Incomplete! ) 到国家代码

python - Scikit/Numpy/Pandas 值错误 : setting an array element with sequence

python - 如何从数据帧的列中提取两个整数值

python - 如何确定给定目录是否在 Python 中被编辑为 `symlink`?

python - Google Cloud Composer BigQuery Operator - 获取作业 API HTTPError 404

python - 按多个轴对 2D numpy 数组进行排序