n维数组 (ndarray

ndarray 是具有相同类型和大小的项目的多维容器(通常为固定大小)。数组中维度和项的数目由其 shape ,这是一个 tuple 属于 N 指定每个维度大小的非负整数。数组中的项类型由单独的 data-type object (dtype) ,其中一个与每个日历关联。

与Python中的其他容器对象一样, ndarray 可以通过访问和修改 indexing or slicing 数组(例如, N 整数),并通过 ndarray .

不同 ndarrays 可以共享相同的数据,以便在一个 ndarray 可能在另一个中可见。也就是说,一个日历可以是 “视图” 到另一个日历,它所引用的数据由 “基地” 恩达雷ndarrays也可以是python拥有的内存的视图 strings 或实现 bufferarray 接口。

例子

2 x 3大小的二维数组,由4字节整数元素组成:

>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<class 'numpy.ndarray'>
>>> x.shape
(2, 3)
>>> x.dtype
dtype('int32')

可以使用类似于python容器的语法对数组进行索引:

>>> # The element of x in the *second* row, *third* column, namely, 6.
>>> x[1, 2]
6

例如 slicing 可以生成数组的视图:

>>> y = x[:,1]
>>> y
array([2, 5])
>>> y[0] = 9 # this also changes the corresponding element in x
>>> y
array([9, 5])
>>> x
array([[1, 9, 3],
       [4, 5, 6]])

构造数组

可以使用中详述的例程构造新数组。 数组创建例程 以及通过使用低水平 ndarray 构造函数:

ndarray [形状] [, dtype, buffer, offset, ...] )

数组对象表示固定大小项的多维同构数组。

索引数组

可以使用扩展的python切片语法对数组进行索引, array[selection] . 类似的语法也用于访问 structured data type .

参见

Array Indexing .

数据数组的内存布局

类的实例 ndarray 由计算机内存的连续一维段(由数组或其他对象拥有)和映射的索引方案组成 N 整数到块中某个项的位置。指数的变化范围由 shape 数组的每个项目占用的字节数和解释字节的方式由 data-type object 与数组关联。

内存的一部分本质上是一维的,并且有许多不同的方案来安排 N -一维块中的一维数组。NumPy 是灵活的,而且 ndarray 对象可以容纳任何 步幅索引方案 . 在跨步方案中,n维索引 (n_0, n_1, ..., n_{{N-1}}) 对应于偏移量(字节):

n \mathrm offset=\sum k=0 ^ n-1 s k n u k

从与数组关联的内存块的开头开始。在这里, s_k 是指定 strides 数组的这个 column-major 顺序(例如,在Fortran语言和 Matlabrow-major 顺序(在C中使用)方案只是特定类型的跨步方案,对应于可以 演说 步步为营:

System Message: WARNING/2 (suk^{\mathrm{column}}=\mathrm{itemsize}\prod{j=0}^{k-1}d\u j,)

latex exited with error [stdout] This is pdfTeX, Version 3.14159265-2.6-1.40.19 (TeX Live 2019/dev/Debian) (preloaded format=latex) restricted \write18 enabled. entering extended mode (./math.tex LaTeX2e <2018-12-01> (/usr/share/texlive/texmf-dist/tex/latex/base/article.cls Document Class: article 2018/09/03 v1.4i Standard LaTeX document class (/usr/share/texlive/texmf-dist/tex/latex/base/size12.clo)) (/usr/share/texlive/texmf-dist/tex/latex/base/inputenc.sty) (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsmath.sty For additional information on amsmath, use the `?' option. (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amstext.sty (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsgen.sty)) (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsbsy.sty) (/usr/share/texlive/texmf-dist/tex/latex/amsmath/amsopn.sty)) (/usr/share/texlive/texmf-dist/tex/latex/amscls/amsthm.sty) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amssymb.sty (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/amsfonts.sty)) (/usr/share/texlive/texmf-dist/tex/latex/anyfontsize/anyfontsize.sty) (/usr/share/texlive/texmf-dist/tex/latex/tools/bm.sty) No file math.aux. (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsa.fd) (/usr/share/texlive/texmf-dist/tex/latex/amsfonts/umsb.fd) LaTeX Warning: Command \u invalid in math mode on input line 14. ! Please use \mathaccent for accents in math mode. \add@accent ...@spacefactor \spacefactor }\accent #1 #2\egroup \spacefactor ... l.14 ...emsize}\prod{j=0}^{k-1}d\u j,\end{split} ! You can't use `\spacefactor' in math mode. \add@accent ...}\accent #1 #2\egroup \spacefactor \accent@spacefactor l.14 ...emsize}\prod{j=0}^{k-1}d\u j,\end{split} ! Package inputenc Error: Unicode character , (U+FF0C) (inputenc) not set up for use with LaTeX. See the inputenc package documentation for explanation. Type H <return> for immediate help. ... l.14 ...emsize}\prod{j=0}^{k-1}d\u j,\end{split} LaTeX Warning: Command \u invalid in math mode on input line 14. ! Please use \mathaccent for accents in math mode. \add@accent ...@spacefactor \spacefactor }\accent #1 #2\egroup \spacefactor ... l.14 ...emsize}\prod{j=0}^{k-1}d\u j,\end{split} ! You can't use `\spacefactor' in math mode. \add@accent ...}\accent #1 #2\egroup \spacefactor \accent@spacefactor l.14 ...emsize}\prod{j=0}^{k-1}d\u j,\end{split} ! Package inputenc Error: Unicode character , (U+FF0C) (inputenc) not set up for use with LaTeX. See the inputenc package documentation for explanation. Type H <return> for immediate help. ... l.14 ...emsize}\prod{j=0}^{k-1}d\u j,\end{split} [1] (./math.aux) ) (see the transcript file for additional information) Output written on math.dvi (1 page, 564 bytes). Transcript written on math.log.

在哪里? d_j = self.shape[j] .

C和Fortran命令都是 contiguousi.e., 单段内存布局,其中内存块的每个部分都可以通过一些索引组合访问。

注解

Contiguous arrayssingle-segment arrays 是同义词,在整个文档中可以互换使用。

虽然具有相应标志集的C样式和Fortran样式连续数组可以用上述跨步进行寻址,但实际跨步可能不同。这有两种情况:

  1. 如果 self.shape[k] == 1 那么对于任何合法的索引 index[k] == 0 . 这意味着在偏移量的公式中 n_k = 0 因此 s_k n_k = 0 以及 s_k = self.strides[k] 是任意的。

  2. 如果数组没有元素 (self.size == 0 )没有合法的索引,而且从未使用跨步。任何没有元素的数组都可以视为C样式和Fortran样式是连续的。

要点1。意味着 selfself.squeeze() 始终具有相同的连续性和 aligned 标志值。这也意味着,即使是高维数组也可以是C样式和Fortran样式同时相邻的。

如果所有元素的内存偏移量和基偏移量本身是 self.itemsize . 理解 memory-alignment 在大多数硬件上都有更好的性能。

注解

编译时环境变量当前可以禁用点(1)和(2) NPY_RELAXED_STRIDES_CHECKING=0 ,这是numpy1.10之前的默认值。任何用户都不应该这样做。 NPY_RELAXED_STRIDES_DEBUG=1 当错误地依赖C扩展代码中的跨步时,可以用来帮助查找错误(参见下面的警告)。

通过查看 np.ones((10,1), order='C').flags.f_contiguous . 如果这是 True ,然后你的 NumPy 有放松的步伐检查启用。

警告

它确实 not 一般认为 self.strides[-1] == self.itemsize 对于C型连续数组或 self.strides[0] == self.itemsize 对于Fortran样式,连续数组为true。

新数据 ndarrays 是在 row-major (c)命令,除非另有规定,但例如, basic array slicing 经常生产 views 在另一个方案中。

注解

numpy中的一些算法在任意跨步数组上工作。然而,有些算法需要单段阵列。当一个不规则的跨步数组被传递到这样的算法中时,就会自动生成一个副本。

数组属性

数组属性反映数组本身固有的信息。通常,通过一个数组的属性访问该数组,可以获取并有时设置该数组的内部属性,而无需创建新的数组。暴露的属性是数组的核心部分,只有部分属性可以在不创建新数组的情况下进行有意义的重置。有关每个属性的信息如下所示。

内存布局

以下属性包含有关数组内存布局的信息:

ndarray.flags 

有关数组内存布局的信息。

ndarray.shape 

数组维度的元组。

ndarray.strides 

遍历数组时要在每个维度中单步执行的字节元组。

ndarray.ndim 

数组维数。

ndarray.data 

python缓冲区对象指向数组数据的开头。

ndarray.size 

数组中的元素数。

ndarray.itemsize 

一个数组元素的长度(字节)。

ndarray.nbytes 

数组元素消耗的总字节数。

ndarray.base 

如果内存来自其他对象,则为基对象。

数据类型

与数组关联的数据类型对象可以在 dtype 属性:

ndarray.dtype 

数组元素的数据类型。

其他属性

ndarray.T 

换位数组。

ndarray.real 

数组的实际部分。

ndarray.imag 

数组的虚部。

ndarray.flat 

数组上的一维迭代器。

ndarray.ctypes 

简化数组与CTypes模块交互的对象。

阵列接口

参见

数组接口 .

__array_interface__

数组接口的python端

__array_struct__

数组接口的C端

ctypes 外部功能接口

ndarray.ctypes 

简化数组与CTypes模块交互的对象。

阵列方法

ndarray 对象有许多方法,它们以某种方式对数组或对数组进行操作,通常返回数组结果。下面简要介绍这些方法。(每个方法的docstring都有更完整的描述。)

对于以下方法,中也有相应的函数 numpyallanyargmaxargminargpartitionargsortchooseclipcompresscopycumprodcumsumdiagonalimagmaxmeanminnonzeropartitionprodptpputravelrealrepeatreshaperoundsearchsortedsortsqueezestdsumswapaxestaketracetransposevar .

数组转换

ndarray.item * ARGs)

将数组的元素复制到标准的python标量并返回它。

ndarray.tolist ()

作为数组返回 a.ndim -Python标量的深度嵌套列表。

ndarray.itemset * ARGs)

将标量插入数组(如果可能,将标量转换为数组的dtype)

ndarray.tostring \ [order] )

的兼容性别名 tobytes ,行为完全相同。

ndarray.tobytes \ [order] )

构造包含数组中原始数据字节的python字节。

ndarray.tofile (FID) [, sep, format] )

将数组以文本或二进制形式写入文件(默认)。

ndarray.dump \(文件)

将数组的pickle转储到指定的文件。

ndarray.dumps ()

以字符串形式返回数组的pickle。

ndarray.astype (dType) [, order, casting, ...] )

数组的副本,强制转换为指定类型。

ndarray.byteswap \ [inplace] )

交换数组元素的字节

ndarray.copy \ [order] )

返回数组的副本。

ndarray.view \ [dtype] [, type] )

具有相同数据的数组的新视图。

ndarray.getfield (dType) [, offset] )

以特定类型返回给定数组的字段。

ndarray.setflags \ [write, align, uic] )

分别设置数组标志可写、对齐(writebackifcopy和updateifcopy)。

ndarray.fill 值(值)

用标量值填充数组。

形状操纵

对于重新整形、调整大小和转置,可以将单个tuple参数替换为 n 将被解释为n元组的整数。

ndarray.reshape [形状] [, order] )

返回包含具有新形状的相同数据的数组。

ndarray.resize \新的形状 [, refcheck] )

就地更改数组的形状和大小。

ndarray.transpose * 轴)

返回转置轴的数组视图。

ndarray.swapaxes \(轴1、轴2)

返回数组的视图 axis1axis2 互换的

ndarray.flatten \ [order] )

返回折叠为一维的数组的副本。

ndarray.ravel \ [order] )

返回扁平数组。

ndarray.squeeze \ [axis] )

从中删除长度为1的轴 a .

项目选择和操作

对于采用 axis 关键字,默认为 None . 如果轴是 None ,然后将数组视为一维数组。任何其他价值 axis 表示操作应沿其进行的维度。

ndarray.take [指数] [, axis, out, mode] )

返回由以下元素组成的数组 a 在给定的指数上。

ndarray.put \(索引,值[, mode] )

集合 a.flat[n] = values[n] 为了所有 n 在索引中。

ndarray.repeat [重复] [, axis] )

重复数组元素。

ndarray.choose [选择] [, out, mode] )

使用索引数组从一组选项中构造新数组。

ndarray.sort \ [axis, kind, order] )

对数组进行就地排序。

ndarray.argsort \ [axis, kind, order] )

返回将对此数组进行排序的索引。

ndarray.partition (KTH) [, axis, kind, order] )

重新排列数组中的元素,使第k个位置的元素值位于排序数组中的位置。

ndarray.argpartition (KTH) [, axis, kind, order] )

返回将对此数组进行分区的索引。

ndarray.searchsorted (V) [, side, sorter] )

查找应在a中插入v元素以保持顺序的索引。

ndarray.nonzero ()

返回非零元素的索引。

ndarray.compress [条件] [, axis, out] )

沿给定轴返回此数组的选定切片。

ndarray.diagonal \ [offset, axis1, axis2] )

返回指定的对角线。

计算

这些方法中的许多都采用名为 axis . 在这种情况下,

  • 如果 axisNone (默认情况下),数组被视为一维数组,并在整个数组上执行操作。如果self是0维数组或数组标量,则此行为也是默认行为。(数组标量是类型/类float32、float64等的实例,而0维数组是仅包含一个数组标量的ndarray实例。)

  • 如果 axis 是一个整数,然后在给定轴上执行操作(对于可以沿给定轴创建的每个一维子数组)。

实例 axis 参数

尺寸为3 x 3 x 3的三维数组,在其三个轴上求和

>>> x = np.arange(27).reshape((3,3,3))
>>> x
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],
       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],
       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
>>> x.sum(axis=0)
array([[27, 30, 33],
       [36, 39, 42],
       [45, 48, 51]])
>>> # for sum, axis is the first keyword, so we may omit it,
>>> # specifying only its value
>>> x.sum(0), x.sum(1), x.sum(2)
(array([[27, 30, 33],
        [36, 39, 42],
        [45, 48, 51]]),
 array([[ 9, 12, 15],
        [36, 39, 42],
        [63, 66, 69]]),
 array([[ 3, 12, 21],
        [30, 39, 48],
        [57, 66, 75]]))

参数 D型 指定应在其上执行缩减操作(如求和)的数据类型。默认的reduce数据类型与 self . 为了避免溢出,可以使用较大的数据类型执行缩减。

对于几种方法,可选 out 还可以提供参数,并将结果放入给定的输出数组中。这个 out 参数必须是 ndarray 并且具有相同数量的元素。它可以具有不同的数据类型,在这种情况下,将执行强制转换。

ndarray.max \ [axis, out, keepdims, initial, ...] )

沿给定轴返回最大值。

ndarray.argmax \ [axis, out] )

返回给定轴上最大值的索引。

ndarray.min \ [axis, out, keepdims, initial, ...] )

沿给定轴返回最小值。

ndarray.argmin \ [axis, out] )

返回沿给定轴的最小值的索引。

ndarray.ptp \ [axis, out, keepdims] )

沿给定轴的峰间(最大-最小)值。

ndarray.clip \ [min, max, out] )

返回值限制为的数组 [min, max] .

ndarray.conj ()

复共轭所有元素。

ndarray.round \ [decimals, out] )

返回 a 每个元素四舍五入到给定的小数位数。

ndarray.trace \ [offset, axis1, axis2, dtype, out] )

沿数组的对角线返回和。

ndarray.sum \ [axis, dtype, out, keepdims, ...] )

返回给定轴上数组元素的和。

ndarray.cumsum \ [axis, dtype, out] )

返回给定轴上元素的累积和。

ndarray.mean \ [axis, dtype, out, keepdims, where] )

返回沿给定轴的数组元素的平均值。

ndarray.var \ [axis, dtype, out, ddof, ...] )

返回数组元素沿给定轴的方差。

ndarray.std \ [axis, dtype, out, ddof, ...] )

返回数组元素沿给定轴的标准偏差。

ndarray.prod \ [axis, dtype, out, keepdims, ...] )

返回数组元素在给定轴上的乘积

ndarray.cumprod \ [axis, dtype, out] )

返回元素沿给定轴的累积积。

ndarray.all \ [axis, out, keepdims, where] )

如果所有元素的计算结果都为true,则返回true。

ndarray.any \ [axis, out, keepdims, where] )

如果的任何元素 a 计算为真。

算术、矩阵乘法和比较运算

上的算术和比较运算 ndarrays 被定义为元素操作,通常产生 ndarray 对象作为结果。

每个算术运算 (+-, *, /, `` /; ``%`divmod()**pow()<<>>&^|~ )以及比较 (==<><=>=!= )相当于相应的通用函数(或 ufunc 简而言之)NumPy 。有关更多信息,请参见 Universal Functions .

比较运算符:

ndarray.__lt__ \(值,/)

返回self<value。

ndarray.__le__ \(值,/)

返回self<=value。

ndarray.__gt__ \(值,/)

返回self>值。

ndarray.__ge__ \(值,/)

返回self>=值。

ndarray.__eq__ \(值,/)

返回self==值。

ndarray.__ne__ \(值,/)

回归自我!=值。

数组的真值 (bool() ):

ndarray.__bool__ (/)

我自己!= 0

注解

数组的真值测试调用 ndarray.__bool__ ,如果数组中的元素数大于1,则会引发错误,因为此类数组的真值不明确。使用 .any().all() 相反,要清楚在这种情况下意味着什么。(如果元素数为0,则数组的计算结果为 False

一元运算:

ndarray.__neg__ (/)

-自我

ndarray.__pos__ (/)

+自我

ndarray.__abs__ (自我)

ndarray.__invert__ (/)

自我

算术:

ndarray.__add__ \(值,/)

返回self+值。

ndarray.__sub__ \(值,/)

返回自身值。

ndarray.__mul__ \(值,/)

返回self*值。

ndarray.__truediv__ \(值,/)

返回自身/值。

ndarray.__floordiv__ \(值,/)

返回self//值。

ndarray.__mod__ \(值,/)

返回self%值。

ndarray.__divmod__ \(值,/)

返回divmod(self,value)。

ndarray.__pow__ \(值[, mod] )

返回pow(self,value,mod)。

ndarray.__lshift__ \(值,/)

返回self<<value。

ndarray.__rshift__ \(值,/)

返回self>>值。

ndarray.__and__ \(值,/)

返回自身值(&V)。

ndarray.__or__ \(值,/)

返回自身值。

ndarray.__xor__ \(值,/)

返回self^值。

注解

  • 任何第三个论点 pow 被静默地忽略,作为底层 ufunc 只接受两个参数。

  • 因为 ndarray 是一个内置类型(用C编写),即 __r{{op}}__ 特殊方法没有直接定义。

  • 为实现数组的许多算术特殊方法而调用的函数可以使用 __array_ufunc__ .

算术,就地:

ndarray.__iadd__ \(值,/)

返回self+=值。

ndarray.__isub__ \(值,/)

返回self-=值。

ndarray.__imul__ \(值,/)

返回self*=值。

ndarray.__itruediv__ \(值,/)

返回self/=值。

ndarray.__ifloordiv__ \(值,/)

返回self/=value。

ndarray.__imod__ \(值,/)

返回self%=值。

ndarray.__ipow__ \(值,/)

返回self**=值。

ndarray.__ilshift__ \(值,/)

返回self<<=value。

ndarray.__irshift__ \(值,/)

返回self>>=值。

ndarray.__iand__ \(值,/)

返回self&=值。

ndarray.__ior__ \(值,/)

返回self=值。

ndarray.__ixor__ \(值,/)

返回self^=值。

警告

就地操作将使用由两个操作数的数据类型决定的精度来执行计算,但会自动降低结果的值(如有必要),以便将其放回数组中。因此,对于混合精度计算, A {{op}}= B 可能不同于 A = A {{op}} B . 例如,假设 a = ones((3,3)) . 然后, a += 3j 不同于 a = a + 3j :虽然它们都执行相同的计算, a += 3 投射结果以适应 aa = a + 3j 重新绑定名称 a 结果。

矩阵乘法:

ndarray.__matmul__ \(值,/)

返回self@value。

注解

矩阵运算符 @@= 在python 3.5中引入了pep465。numpy 1.10.0初步实现了 @ 用于测试。更多文件见 matmul 文档。

特殊方法

对于标准库函数:

ndarray.__copy__ ()

使用如果 copy.copy 对数组调用。

ndarray.__deepcopy__ (备忘录,)

使用如果 copy.deepcopy 对数组调用。

ndarray.__reduce__ ()

酸洗。

ndarray.__setstate__ \(状态,/)

用于酸洗。

基本自定义:

ndarray.__new__ * ARGs, *  * 克瓦格斯)

创建并返回新对象。

ndarray.__array__ \ [dtype] , /)

如果未给定dtype,则返回对self的新引用;如果dtype与数组的当前dtype不同,则返回所提供数据类型的新数组。

ndarray.__array_wrap__ [(Obj])

容器自定义:(请参见 Indexing

ndarray.__len__ (/)

返回len(self)。

ndarray.__getitem__ \(键,/)

回归自我 [key] .

ndarray.__setitem__ \(键,值,/)

设置自我 [key] 重视。

ndarray.__contains__ \(键,/)

自己返回钥匙。

转换;操作 int()float()complex() . 它们只在包含一个元素的数组上工作,并返回相应的标量。

ndarray.__int__ (自我)

ndarray.__float__ (自我)

ndarray.__complex__ 

字符串表示:

ndarray.__str__ (/)

返回str(self)。

ndarray.__repr__ (/)

返回repr(self)。