嵌套结构的Numpy数组 [英] Nested Structured Numpy Array

查看:426
本文介绍了嵌套结构的Numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建以下格式的结构化数组:

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.

推荐答案

您需要给dtype的第二个元素命名,请尝试:

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')])])

请原谅我进行编辑,但是我发现rec-array很难在没有嵌套的情况下使用,如果将dtype展平,会不会放松很多?

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?

更新:

您的嵌套比我想象的还要多.试试这个:

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')])])])

这篇关于嵌套结构的Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆