numpy.ndarray.view#
method
- ndarray.view([dtype][, type])#
具有相同数据的数组的新视图.
备注
为
dtype传递 None 与省略该参数不同,因为前者会调用dtype(None),它是dtype('float64')的别名.- 参数:
- dtypedata-type or ndarray sub-class, optional
返回视图的数据类型描述符,例如,float32 或 int16.省略它会导致该视图具有与 a 相同的数据类型.此参数也可以指定为 ndarray 子类,然后指定返回对象的类型(这等效于设置
type参数).- typePython 类型,可选
返回视图的类型,例如,ndarray 或 matrix.同样,省略该参数会导致类型保留.
注释
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的最后一个轴必须是连续的. 该轴将在结果中调整大小.在 1.23.0 版本发生变更: 只有最后一个轴需要是连续的. 以前,整个数组必须是 C 连续的.
示例
>>> import numpy as np >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
使用不同的类型和 dtype 查看数组数据:
>>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)]) >>> y = x.view(dtype=nonneg, type=np.recarray) >>> x["a"] array([-1], dtype=int8) >>> y.a array([255], dtype=uint8)
在结构化数组上创建视图,使其可用于计算
>>> 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] np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
对于由切片,转置,Fortran 排序等定义的数组,通常应避免更改 dtype 大小(每个条目的字节数)的视图:
>>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16) >>> y = x[:, ::2] >>> y array([[1, 3], [4, 6]], 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 last axis must be contiguous >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 3)], [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
但是,对于具有连续最后一个轴的数组,即使其余轴不是 C 连续的,更改 dtype 的视图也完全没问题:
>>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4) >>> x.transpose(1, 0, 2).view(np.int16) array([[[ 256, 770], [3340, 3854]], [[1284, 1798], [4368, 4882]], [[2312, 2826], [5396, 5910]]], dtype=int16)