1

I've read through the documentation but cannot work out how to create a structured array of strings and integers with numpy. A shortened version of my problem is below:

foo = [['asd', 1, 2],['bgf',2,3]]
bar = np.array(foo, dtype=['S10', 'i4','i4'])

I would then like to have bar[:,0] as an array of strings and bar[:,1]and bar[:,2] as arrays of integers.

Unfortunately this gives a TypeError: data type not understood. I've tried many other ways to get it to work but cannot find anything intuitive.

Currently I am just doing bar = np.array(foo) and then casting to integer whenever I call a value from the 2nd or 3rd column, which is far from ideal.

How can I create the structure array bar that I would like from the list of lists foo?

2 Answers 2

2

Here's one way to create the structured array:

>>> foo = [('asd', 1, 2),('bgf',2,3)]
>>> bar = np.array(foo, dtype='S10,i4,i4')
>>> bar
array([('asd', 1, 2), ('bgf', 2, 3)], 
      dtype=[('f0', 'S10'), ('f1', '<i4'), ('f2', '<i4')])
>>> bar['f0']
array(['asd', 'bgf'], 
      dtype='|S10')
>>> bar['f1']
array([1, 2], dtype=int32)
>>> bar['f2']
array([2, 3], dtype=int32)

If you want a normal array, with elements rather than fields, then use dtype=object.

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

Comments

1

If there is more than one datatype in an array, use dtype=object.

>>> bar = np.array(foo, dtype=object)
>>> bar[:,0]
array(['asd', 'bgf'], dtype=object)
>>> bar[:,1]
array([1, 2], dtype=object)
>>> bar[:,2]
array([2, 3], dtype=object)

Comments

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.