Reputation: 1997
I need to parse a ndarray to a fixed shape. I need help in using the dtype, so it parse the full array, not just the first match.
a
Out[193]: '1\t2\t3\t4\t5\t6\t'
ar = np.loadtxt(StringIO(a),dtype={'names':('x','y'),'formats':('f8','f8')}).view(np.recarray)
ar.x
Out[195]: array(1.0)
ar.y
Out[196]: array(2.0)
Being that I wanted:
ar.x
Out[195]: array(1.0,3.0,5.0)
ar.y
Out[196]: array(2.0,4.0,6.0)
If someone could explain the settings in dtype that make it happend would be very nice =)
Upvotes: 2
Views: 434
Reputation: 1460
The problem is not with your dtype, it's that you're using an array of the wrong shape (1D instead of 2D). There are a bunch of ways you could approach reshaping your data, but this is the easiest I could come up with assuming you actually need to use loadtxt like that:
raw = np.loadtxt(StringIO(a), dtype='f8')
resh = raw.reshape(-1,2) # This will work for any (even) length initial data
rec = resh.view([('x', 'f8'), ('y', 'f8')], np.recarray)
Note the -1 shape means, "whatever makes things work out so the other dimensions are right."
Upvotes: 2