访问Numpy结构化数组中的元素

2024-03-29 12:37:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一种情况,我想做以下事情:

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数据类型创建索引有什么建议吗?在

谢谢


Tags: tonumpydataindexnp情况事情do