如何在numpy结构化数组中返回多个列的视图

ask*_*han 23 python arrays numpy

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

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')])
Run Code Online (Sandbox Code Playgroud)

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

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)]
Run Code Online (Sandbox Code Playgroud)

如果我只选择一列,那就是一个视图:

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

print c
#[ 99.  4.   3. ]

print a['y']
#[ 99.  4.   3. ]
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以同时获得多个列的查看行为?

我有两个解决方法,一个是循环遍历列,另一个是创建一个层次结构dtype,以便一列实际返回一个带有我想要的两个(或更多)字段的结构化数组.不幸的是,zip还会返回一份副本,所以我做不到:

x = a['x']; y = a['y']
z = zip(x,y)
z[0] = (9.,9.)
Run Code Online (Sandbox Code Playgroud)

HYR*_*YRY 31

您可以创建一个dtype对象,其中只包含您想要的字段,并用于numpy.ndarray()创建原始数组的视图:

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)
Run Code Online (Sandbox Code Playgroud)

这是输出:

[(10, 0.0, 100, 0L) (1000, 3.14, 7, 65536L) (1000, 3.14, 7, 65536L)]
Run Code Online (Sandbox Code Playgroud)

  • 哦,这很好,适用于非连续(或不规则间隔)的字段. (2认同)

Chr*_*erC 9

在@ HYRY的答案的基础上,你也可以使用ndarray方法getfield:

def fields_view(array, fields):
    return array.getfield(numpy.dtype(
        {name: array.dtype.fields[name] for name in fields}
    ))
Run Code Online (Sandbox Code Playgroud)


And*_*rom 6

从 Numpy 1.13 版开始,您建议的代码返回一个视图。请参阅此页面上的“NumPy 1.12.0 发行说明->未来更改->结构化数组的多字段操作”:

https://docs.scipy.org/doc/numpy-dev/release.html

  • 仅在 numpy 1.16 中实现了此功能 (4认同)

Jai*_*ime 5

我不认为有一个简单的方法可以实现你想要的。一般来说,您不能对数组采取任意视图。请尝试以下操作:

>>> a
array([(1.5, 2.5, [[1.0, 2.0], [1.0, 2.0]]),
       (3.0, 4.0, [[4.0, 5.0], [4.0, 5.0]]),
       (1.0, 3.0, [[2.0, 6.0], [2.0, 6.0]])], 
      dtype=[('x', '<f8'), ('y', '<f8'), ('value', '<f8', (2, 2))])
>>> a.view(float)
array([ 1.5,  2.5,  1. ,  2. ,  1. ,  2. ,  3. ,  4. ,  4. ,  5. ,  4. ,
        5. ,  1. ,  3. ,  2. ,  6. ,  2. ,  6. ])
Run Code Online (Sandbox Code Playgroud)

记录数组的浮动视图显示实际数据如何存储在内存中。对这些数据的看法必须可以表达为上述数据的形状、步幅和偏移量的组合。因此,例如,如果您只想查看'x''y'仅查看,您可以执行以下操作:

>>> from numpy.lib.stride_tricks import as_strided
>>> b = as_strided(a.view(float), shape=a.shape + (2,),
                   strides=a.strides + a.view(float).strides)
>>> b
array([[ 1.5,  2.5],
       [ 3. ,  4. ],
       [ 1. ,  3. ]])
Run Code Online (Sandbox Code Playgroud)

as_strided作用与也许更容易理解的相同:

>>> bb = a.view(float).reshape(a.shape + (-1,))[:, :2]
>>> bb
array([[ 1.5,  2.5],
       [ 3. ,  4. ],
       [ 1. ,  3. ]])
Run Code Online (Sandbox Code Playgroud)

这两者都是对以下内容的看法 a

>>> b[0,0] =0
>>> a
array([(0.0, 2.5, [[0.0, 2.0], [1.0, 2.0]]),
       (3.0, 4.0, [[4.0, 5.0], [4.0, 5.0]]),
       (1.0, 3.0, [[2.0, 6.0], [2.0, 6.0]])], 
      dtype=[('x', '<f8'), ('y', '<f8'), ('value', '<f8', (2, 2))])
>>> bb[2, 1] = 0
>>> a
array([(0.0, 2.5, [[0.0, 2.0], [1.0, 2.0]]),
       (3.0, 4.0, [[4.0, 5.0], [4.0, 5.0]]),
       (1.0, 0.0, [[2.0, 6.0], [2.0, 6.0]])], 
      dtype=[('x', '<f8'), ('y', '<f8'), ('value', '<f8', (2, 2))])
Run Code Online (Sandbox Code Playgroud)

如果这两者中的任何一个都可以转换为记录数组,那就太好了,但 numpy 拒绝这样做,原因对我来说不太清楚:

>>> b.view([('x',float), ('y',float)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: new type not compatible with array.
Run Code Online (Sandbox Code Playgroud)

当然,什么对(某种程度上)有效,'x'什么'y'无效,例如,对于'x''value',所以一般来说答案是:它无法完成。