我可以在 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/