Nested array of structured numbers

I am trying to create a structured array in the following format:

import numpy as np
x = np.array([(2009, (('USA', 10.), ('CHN', 12.))), (2010, (('BRA', 10.), 
    ('ARG', 12.)))], dtype=[('year', '<i4'), [('iso','a3'), ('value','<f4')]])


but it keeps telling me to enter a valid datatype and I'm not sure how to proceed. I can do this just fine if the nested array is in the same format, i.e. all integers:

np.array([('ABC', ((1, 2, 3), (1, 2, 3))), ('CBA', ((3, 2, 1), (3, 2, 1)))],
    dtype='a3, (2, 3)i')


Any help or suggestions would be greatly appreciated.


source to share

1 answer

You need to specify the second element of your dtype name, try:

>>> dtype=[('year', '<i4'), ('item_name', [('iso','a3'), ('value','<f4')])]
>>> np.zeros(3, dtype=dtype)
array([(0, ('', 0.0)), (0, ('', 0.0)), (0, ('', 0.0))], 
      dtype=[('year', '<i4'), ('item_name', [('iso', '|S3'), ('value', '<f4')])])


Forgive me for editing, but I find rec arrays hard enough to work without a socket, would you be losing a lot if you just flattened the dtype?


You have one more level of nesting than I understood. Try the following:

>>> dtype=[('year', '<i4'), ('countries', [('c1', [('iso','a3'), ('value','<f4')]), ('c2', [('iso','a3'), ('value','<f4')])])]
>>> np.array([(2009, (('USA', 10.), ('CHN', 12.))), (2010, (('BRA', 10.), ('ARG', 12.)))], dtype)
array([(2009, (('USA', 10.0), ('CHN', 12.0))),
    (2010, (('BRA', 10.0), ('ARG', 12.0)))], 
    dtype=[('year', '<i4'), ('countries', [('c1', [('iso', '|S3'), ('value', '<f4')]), ('c2', [('iso', '|S3'), ('value', '<f4')])])])




All Articles