2

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 =)

1 Answer 1

2

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."

Sign up to request clarification or add additional context in comments.

2 Comments

ValueError: Cannot specify output type twice.
I guess you figured it out, but I reversed the order of the .view() arguments. Fixed it in my edit. Sorry!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.