gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:31:46 26 4
gpt4 key购买 nike

非常简单的问题:我有一个包含多列的结构化数组,我只想用另一个预先存在的数组填充其中的一些(但不止一个)。

这就是我正在尝试的:

strc = np.zeros(4, dtype=[('x', int), ('y', int), ('z', int)])
x = np.array([2, 3])
strc[['x', 'y']][0] = x

这给了我这个 future 的警告:

main:1: FutureWarning: Numpy has detected that you (may be) writing to an array returned by numpy.diagonal or by selecting multiple fields in a record array. This code will likely break in a future numpy release -- see numpy.diagonal or arrays.indexing reference docs for details. The quick fix is to make an explicit copy (e.g., do arr.diagonal().copy() or arr[['f0','f1']].copy()).

但即使这是一个警告,结构化数组也不会被填充。到目前为止,我正在遍历两个数组并且它有效,但我想这是非常低效的。有没有更好的办法?

最佳答案

如果所有的字段有相同的数据类型,你可以创建一个 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

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

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)]

关于python - numpy:如何一次填充结构化数组中的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21818140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com