gpt4 book ai didi

python - 逐行读取csv文件并保存满足特定条件的行

转载 作者:行者123 更新时间:2023-12-05 02:14:07 25 4
gpt4 key购买 nike

我有一个问题已经在几个主题中讨论过,不过我想更深入一点,也许会找到更好的解决方案。

所以我的想法是用 python 遍历“巨大的”(50 到 60GB).csv 文件,找到满足某些条件的行,提取它们,最后将它们存储在第二个变量中以供进一步分析。

最初问题出在我使用 sparklyr 连接管理的 r 脚本,或者最终是 bash 中的一些 gawk 代码(参见 awk 或 gawk),以提取我需要的数据,然后使用 R/python 对其进行分析。

我想专门用 python 解决这个问题,我的想法是避免混合使用 bash/python 或 bash/R (unix) 等语言。到目前为止,我使用 open as x,逐行浏览文件,它有点管用,但速度非常慢。例如,浏览文件非常快(每秒约 500.000 行,即使 58M 行也可以),但是当我尝试存储数据时,速度下降到每秒约 10 行。对于约 300.000 行的提取,这是 Not Acceptable 。

我尝试了几种解决方案,我猜它不是最优的(糟糕的 python 代码?:( ) 最终会出现更好的解决方案。

解决方案 1: 遍历文件,拆分列表中的行,检查条件,如果可以,则将行放入 numpy 矩阵和满足条件的每次迭代的 vstack(非常慢)

import csv
import numpy
import pandas
from tqdm import tqdm

date_first = '2008-11-01'
date_last = '2008-11-10'

a = numpy.array(['colnames']*35) #data is 35 columns
index = list()

with open("data.csv", "r") as f:
for line in tqdm(f, unit = " lines per"):
line = line.split(sep = ";") # csv with ";" ...
date_file = line[1][0:10] # date stored in the 2nd column

if date_file >= date_first and date_file <= date_last : #data extraction concern a time period (one month for example)
line=numpy.array(line) #go to numpy
a=numpy.vstack((a, line)) #stack it

解决方案 2: 相同,但如果条件正常(非常慢),则将该行存储在带有行索引的 pandas data.frame 中

import csv
import numpy
import pandas
from tqdm import tqdm

date_first = '2008-11-01'
date_last = '2008-11-10'
row = 0 #row index
a = pandas.DataFrame(numpy.zeros((0,35)))#data is 35 columns

with open("data.csv", "r") as f:
for line in tqdm(f, unit = " lines per"):
line = line.split(sep = ";")
date_file = line[1][0:10]

if date_file>=date_first and date_file<=date_last :
a.loc[row] = line #store the line in the pd.data.frame at the position row
row = row + 1 #go to next row

解决方案 3: 相同,但不是将行存储在某处,这对我来说是主要问题,保留一个索引以满足行,然后打开包含我需要的行的 csv < em>(更慢,实际上通过文件查找索引已经足够快了,开始索引的行非常慢)

import csv
import numpy
import pandas
from tqdm import tqdm

date_first = '2008-11-01'
date_last = '2008-11-10'
row = 0
index = list()

with open("data.csv", "r") as f:
f = csv.reader(f, delimiter = ";")
for line in tqdm(f, unit = " lines per"):
line = line.split(sep = ";")
date_file = line[1][0:10]
row = row + 1
if date_file>=date_first and date_file<=date_last :
index.append(row)

with open("data.csv") as f:
reader=csv.reader(f)
interestingrows=[row for idx, row in enumerate(reader) if idx in index]

我们的想法是只保留满足条件的数据,这里是特定月份的提取数据。我不明白问题出在哪里,将数据保存在某处(vstack,或在 pd.DF 中写入)绝对是一个问题。我很确定我做错了什么,但我不确定哪里/什么。

数据是一个包含 35 列和超过 5700 万行的 csv。感谢阅读

哦。

最佳答案

追加到数据帧和 numpy 数组非常昂贵,因为每次追加都必须将整个数据复制到新的内存位置。相反,您可以尝试分 block 读取文件、处理数据,然后追加回来。在这里,我选择了 100,000 的 block 大小,但您显然可以更改它。

我不知道您的 CSV 的列名,所以我猜测是 'date_file'。这应该让你接近:

import pandas as pd

date_first = '2008-11-01'
date_last = '2008-11-10'

df = pd.read_csv("data.csv", chunksize=100000)

for chunk in df:
chunk = chunk[(chunk['date_file'].str[:10] >= date_first)
& (chunk['date_file'].str[:10] <= date_last)]
chunk.to_csv('output.csv', mode='a')

关于python - 逐行读取csv文件并保存满足特定条件的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54145433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com