我有一种情况,我想做到以下几点:在NumPy的结构数组访问元素
import numpy as np
type1 = np.dtype([('col1', 'i'), ('col2', 'i')])
type2 = np.dtype([('cols', type1), ('info', 'S32')])
data = np.zeros(10, type2)
# The following doesn't work, but I want to do something similar
index = ['cols']['col1']
# Set column ['cols']['col1'] to 5
data[index] = 5
# I can only get this to work if I do the following:
index = "['cols']['col1']"
eval('data' + index '= 5') # kinda scary
这是不行的,但我发现使用exec
功能的方法,但那种感觉很哈克。有没有人有任何建议如何以编程方式为嵌套结构化numpy数据类型创建索引?
感谢
为什么你不能用'数据[ '的cols'] [ 'COL1'] = 5'? – user3148185
,因为我需要能够在不幸的是单独的步骤来定义的索引。 – user985030
如果你定义他们像'索引1,索引2 = '的cols',“col1''和使用'数据[索引1] [索引2]'? – user3148185