且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

numpy:如何一次填充结构化数组中的多个字段

更新时间:2023-11-09 21:07:22

如果所有字段都具有相同的dtype,则可以创建视图:

If all the field have the same dtype, you can create a view:

import numpy as np
strc = np.zeros(4, dtype=[('x', int), ('y', int), ('z', int)])
strc_view = strc.view(int).reshape(len(strc), -1)
x = np.array([2, 3])
strc_view[0, [0, 1]] = x

如果您想要一个可以创建任何结构化数组的列视图的通用解决方案,则可以尝试:

If you want a common solution that can create columns views of any structured array, you can try:

import numpy as np
strc = np.zeros(3, dtype=[('x', int), ('y', float), ('z', int), ('t', "i8")])

def fields_view(arr, fields):
    dtype2 = np.dtype({name:arr.dtype.fields[name] for name in fields})
    return np.ndarray(arr.shape, dtype2, arr, 0, arr.strides)

v1 = fields_view(strc, ["x", "z"])
v1[0] = 10, 100

v2 = fields_view(strc, ["y", "z"])
v2[1:] = [(3.14, 7)]

v3 = fields_view(strc, ["x", "t"])

v3[1:] = [(1000, 2**16)]

print strc

这是输出:

[(10, 0.0, 100, 0L) (1000, 3.14, 7, 65536L) (1000, 3.14, 7, 65536L)]