我有一种情况,我想做以下事情:
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数据类型创建索引?
由于
答案 0 :(得分:1)
这样可行:
index = ['cols', 'col1']
data[index[0]][index[1]] = 5
<强>更新强>
这允许在任何深度设置值:
def set_deep(obj, names, value):
if len(names) > 1:
obj = obj[names[0]]
if len(names) > 2:
for name in names[1:-1]:
obj = obj[name]
obj[names[-1]] = value
用法:
set_deep(data, ['cols', 'col1'], 5)
set_deep(data, ['a', 'b', 'c', 'd'], 5)