繁体   English   中英

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

[英]Accessing Elements in a Numpy Structured Array

我遇到以下情况,我想执行以下操作:

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函数的解决方法,但感觉很hacky。 有人对如何以编程方式为嵌套的结构化numpy数据类型创建索引有任何建议吗?

谢谢

这将工作:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM