python - 如何返回numpy结构化数组中多列的 View

标签 python arrays numpy

我可以在 numpy 结构化数组中一次看到几列(fields),例如,通过使用字段名称列表进行索引

import numpy as np

a = np.array([(1.5, 2.5, (1.0,2.0)), (3.,4.,(4.,5.)), (1.,3.,(2.,6.))],
        dtype=[('x',float), ('y',float), ('value',float,(2,2))])

print a[['x','y']]
#[(1.5, 2.5) (3.0, 4.0) (1.0, 3.0)]

print a[['x','y']].dtype
#[('x', '<f4') ('y', '<f4')])

但问题是它似乎是一个副本而不是一个 View :

b = a[['x','y']]
b[0] = (9.,9.)

print b
#[(9.0, 9.0) (3.0, 4.0) (1.0, 3.0)]

print a[['x','y']]
#[(1.5, 2.5) (3.0, 4.0) (1.0, 3.0)]

如果我只选择一列,那就是 View :

c = x['y']
c[0] = 99.

print c
#[ 99.  4.   3. ]

print a['y']
#[ 99.  4.   3. ]

有什么方法可以一次获取多个列的 View 行为?

我有两种解决方法,一种是仅循环遍历列,另一种是创建分层dtype,以便一列实际上返回具有两个(或更多)的结构化数组我想要的字段。不幸的是, zip 也返回一个副本,所以我不能这样做:

x = a['x']; y = a['y']
z = zip(x,y)
z[0] = (9.,9.)

最佳答案

你可以创建一个只包含你想要的字段的 dtype 对象,并使用 numpy.ndarray() 创建一个原始数组的 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结构化数组中多列的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15182381/

相关文章:

python - 求解稀疏矩阵的线性回归方程

python - 只能连接 str 不能列表到 str

python - 使用接口(interface)在 Windows 上将 python 脚本作为服务运行

c# - 数组到列表——无法使 AddRange(IEnumerable) 工作

php - 引用 - 这个错误在 PHP 中意味着什么?

python - 如何从 numpy 数组生成音频?

python - 对未知公式的数据集进行曲线拟合 (SciPy)

Python解析超过4GB的大数据库

python - 如何将自定义函数应用于 PyTorch 矩阵中的特定列

javascript - ReactJS 在渲染状态下循环