具有相同数据的数组的新视图。
参数:dtype: : data-type 或 ndarray sub-class, 可选参数
返回视图的数据类型描述符,例如float32或int16。默认值为None(无),导致视图具有与a相同的数据类型。此参数也可以指定为ndarray sub-class,然后它指定返回对象的类型(这等效于设置type参数)。
type: : Python type, 可选参数
返回视图的类型,例如ndarray或matrix。同样,默认值None将导致类型保留。
注意:
a.view()有两种不同的用法:
a.view(some_dtype)或者a.view(dtype=some_dtype)使用不同的数据类型构造阵列内存的视图。这可能导致对内存字节的重新解释。
a.view(ndarray_subclass)或者a.view(type=ndarray_subclass)只是返回一个ndarray_subclass实例,该实例看起来在相同的数组(相同的形状,dtype等)。这不会导致对内存的重新解释。
对于a.view(some_dtype)如果some_dtype每个条目的字节数与以前的dtype的字节数不同(例如,将常规数组转换为结构化数组),则无法仅根据的表面外观来预测视图的行为a(显示为print(a))。这也取决于具体如何a存储在内存中。因此,如果a如果将C-ordered与fortran-ordered进行比较,并且将其定义为切片或转置等,则视图可能会给出不同的结果。
例子:
>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
使用不同的type和dtype查看数组数据:
>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)
>>> print(type(y))
在结构化数组上创建视图,以便可以在计算中使用它
>>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
>>> xv = x.view(dtype=np.int8).reshape(-1,2)
>>> xv
array([[1, 2],
[3, 4]], dtype=int8)
>>> xv.mean(0)
array([2., 3.])
对视图进行更改会更改基础数组
>>> xv[0,1] = 20
>>> x
array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
使用视图将数组转换为RecArray:
>>> z = x.view(np.recarray)
>>> z.a
array([1, 3], dtype=int8)
视图共享数据:
>>> x[0] = (9, 10)
>>> z[0]
(9, 10)
通常应在由切片,转置,fortran-ordering等定义的数组上避免更改dtype大小(每个条目的字节数)的视图:
>>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16)
>>> y = x[:, 0:2]
>>> y
array([[1, 2],
[4, 5]], dtype=int16)
>>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
Traceback (most recent call last):
...
ValueError:To change to a dtype of a different size, the array must be C-contiguous
>>> z = y.copy()
>>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
array([[(1, 2)],
[(4, 5)]], dtype=[('width', '