Let's say I have some data stored as
"this is row -1 and column -1 with value", 12345
in a csv file. (It's not actually stored like that, the point is the first value in the csv is a string that contains the necessary coordinates.)
I should now like to extract these values. I could do a for r in rows: ...
but I want to do it with a reduce.
import numpy as np
import scipy as sp
from functools import reduce
import csv
import re
def load(filename):
with open(filename,'r') as f:
rows = csv.reader(f)
next(rows) # skip header
coordi,coordj,values = reduce(
lambda aux,r: ([aux[0]+[i], aux[1]+[j], aux[2] + [int(r[1])]] for i,j in [int(d) for d in re.findall(r"\d+", r[0])]),
rows,
[[],[],[]]
)
return coordi, coordj, values
Which produces a
TypeError: 'int' object is not iterable
Since
def load(filename):
with open(filename,'r') as f:
rows = csv.reader(f)
next(rows) # skip header
coordi,coordj,values = reduce(
lambda aux,r: ([aux[0]+[-1], aux[1]+[-1], aux[2] + [int(r[1])]]),
rows,
[[],[],[]]
)
return coordi, coordj, values
Works, I can only guess that there's something about i,j
python isn't happy with.
Which I have no idea why because
for r in rows:
i,j = [int(d) for d in re.findall(r"\d+", row[0])]
works like a charm.
How do I make this work?