【问题标题】:numpy: how to fill multiple fields in a structured array at oncenumpy:如何一次填充结构化数组中的多个字段
【发布时间】:2014-02-16 23:17:10
【问题描述】:

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

这就是我正在尝试的:

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

这给了我这个未来的警告:

ma​​in:1:FutureWarning:Numpy 检测到您(可能)正在写入数组 由 numpy.diagonal 或通过选择记录中的多个字段返回 大批。此代码可能会在未来的 numpy 版本中中断—— 有关详细信息,请参阅 numpy.diagonal 或 arrays.indexing 参考文档。 快速解决方法是制作一个明确的副本(例如,做 arr.diagonal().copy() 或 arr[['f0','f1']].copy())。

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

【问题讨论】:

标签: python numpy structured-array


【解决方案1】:

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

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

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

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

【讨论】:

  • 谢谢你HYRY,我认为你的解决方案对于我的小效率不安来说太过分了,但它可能对其他人有用
猜你喜欢
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多