I have a CSV with 5+ million rows and I want to filter it:
with open("test1.csv") as csv_file:
writer =csv.writer(outputfile, delimiter=',')
for row in csv.reader(csv_file, delimiter=','):
row = [int(x) for x in row]
for i in range (1,11):
if add_i (row) == True:
break
elif row not in (row_dup):
row_dup.append(row)
writer.writerow(row)
I have many functions, the simplest one being add_i
which you can see in the snippet above.
if row[0:3] == range(row[0], row[0] +3 * i, i):
return True
row_dup = []
is an empty array I use to store duplicates so that they don't get written to the file.
I want to improve the execution time of my script, but it takes hours. According to the calculation of a friend, it takes 530 hours or so. I'm not sure about that but regardless, it is still taking a long time.
How I tried to improve the speed of the script:
- Using PyPy but I didn't notice a significant improvement.
- Removing
row = [int(x) for x in row]
but then I'd have to writeif [int(x) for x in row[0:4]] == range(int(row[0]), int(row[0]) + 4 * i, i):
it's annoying and there's still afor
loop. - Removing
for i in range (1,11)
but then I would have to write the indexes myself. Removing
for i in range (1,11)
androw = [int(x) for x in row]
and doing it like soif (int(row[0]) + 1 == int(row[1])) and int(row[1]) + 1 == int(row[2]) and int(row[2]) + 1 == int(row[3]) and int(row[3]) + 1 == int(row[4]): do something
This is a desperate plan and the most annoying. I get rid of two
for
loops and do everything by hand, increasing the index value from 1 to 11 by copy pasting.Considered using Hadoop but the VPS I have are so much less powerful than my PC, low end box.
Considered using SQLite instead of CSV but not convinced it would make things much faster.
Considered writing it in C++, and in fact the first version was in C++ but moved to Python since I didn't notice a big difference and because it's easier to plot in Python.
And by the way, I'm on Manjaro 64 bit, filesystem Ext4, Python 2.7, running in virtualenv. I'm only using a CSV module. I have an HP Pavilion G6 laptop, if you want to see the specs of it.
Note that the code is taking that much time, even though I'm only testing with add_i
so I didn't even bother testing the complicated function. Who knows how much time it would take then.