[Numpy-discussion] genfromtxt converter question

gary ruben gruben at bigpond.net.au
Fri Jun 17 00:36:15 EDT 2011


I'm trying to read a file containing data formatted as in the
following example using genfromtxt and I'm doing something wrong. It
almost works. Can someone point out my error, or suggest a simpler
solution to the ugly converter function? I thought I'd leave in the
commented-out line for future reference, which I thought was a neat
way to get genfromtxt to show what it is trying to pass to the
converter.

import numpy as np
from StringIO import StringIO

a = StringIO('''\
 (-3.9700,-5.0400) (-1.1318,-2.5693) (-4.6027,-0.1426) (-1.4249, 1.7330)
 (-5.4797, 0.0000) ( 1.8585,-1.5502) ( 4.4145,-0.7638) (-0.4805,-1.1976)
 ( 0.0000, 0.0000) ( 6.2673, 0.0000) (-0.4504,-0.0290) (-1.3467, 1.6579)
 ( 0.0000, 0.0000) ( 0.0000, 0.0000) (-3.5000, 0.0000) ( 2.5619,-3.3708)
''')

#~ b = np.genfromtxt(a,converters={1:lambda x:str(x)},dtype=object,delimiter=18)
b = np.genfromtxt(a,converters={1:lambda
x:complex(*eval(x))},dtype=None,delimiter=18,usecols=range(4))

print b

--

This produces
[ (' (-3.9700,-5.0400)', (-1.1318-2.5693j), ' (-4.6027,-0.1426)', '
(-1.4249, 1.7330)')
 (' (-5.4797, 0.0000)', (1.8585-1.5502j), ' ( 4.4145,-0.7638)', '
(-0.4805,-1.1976)')
 (' ( 0.0000, 0.0000)', (6.2673+0j), ' (-0.4504,-0.0290)', ' (-1.3467, 1.6579)')
 (' ( 0.0000, 0.0000)', 0j, ' (-3.5000, 0.0000)', ' ( 2.5619,-3.3708)')]

which I just need to unpack into a 4x4 array, but I get an error if I
try to apply a different view.

thanks,
Gary



More information about the NumPy-Discussion mailing list