I am trying to create a structured array in the below 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 data type and I am not sure how to proceed. I am able to 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.
You need to give the second element of your dtype a 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 editorializing, but I find rec-arrays hard enough to work with without the nesting, would you loose a lot if you just flattened the dtype?
update:
You have one more level of nesting than I realized. Try this:
>>> 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')])])])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With