NumPy-1-26-中文文档-三-
NumPy 1.26 中文文档(三)
NumPy 许可证
Copyright (c) 2005-2023, NumPy Developers.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the NumPy Developers nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
NumPy 参考
发布:
1.26
日期:
2023 年 9 月 16 日
此参考手册详细介绍了 NumPy 中包含的函数、模块和对象,描述了它们的作用和功能。要了解如何使用 NumPy,请参阅完整文档。
-
数组对象
-
N 维数组 (
ndarray
) -
标量
-
数据类型对象 (
dtype
) -
索引例程
-
对数组进行迭代
-
标准数组子类
-
掩码数组
-
数组接口协议
-
日期时间和时间增量
-
-
数组 API 标准兼容性
numpy.array_api
和numpy
之间的差异表
-
常量
-
Inf
-
Infinity
-
NAN
-
NINF
-
NZERO
-
NaN
-
PINF
-
PZERO
-
e
-
euler_gamma
-
inf
-
infty
-
nan
-
newaxis
-
pi
-
-
通用函数 (
ufunc
)-
ufunc
-
可用的通用函数
-
-
例程
-
数组创建例程
-
数组操作例程
-
二进制操作
-
字符串操作
-
C 类型外部函数接口 (
numpy.ctypeslib
) -
日期时间支持函数
-
数据类型例程
-
带有自动域的数学函数
-
浮点数错误处理
-
离散傅里叶变换 (
numpy.fft
) -
函数式编程
-
NumPy 特定的帮助函数
-
输入和输出
-
线性代数 (
numpy.linalg
) -
逻辑函数
-
掩码数组操作
-
数学函数
-
矩阵库 (
numpy.matlib
) -
杂项例程
-
填充数组
-
多项式
-
随机抽样 (
numpy.random
) -
集合例程
-
排序、搜索和计数
-
统计
-
测试支持(
numpy.testing
) -
对测试覆盖(
numpy.testing.overrides
)的支持 -
窗口函数
-
-
键入(
numpy.typing
)-
Mypy 插件
-
与运行时 NumPy API 的差异
-
API
-
-
全局状态](global_state.html)
-
与性能相关的选项
-
与调试相关的选项
-
测试计划的未来行为
-
-
打包(
numpy.distutils
)-
numpy.distutils
中的模块 -
配置类
-
构建可安装的 C 库
-
.src
文件的转换
-
-
NumPy distutils - 用户指南
-
SciPy 结构
-
SciPy 包的要求
-
The
setup.py
文件 -
The
__init__.py
文件 -
NumPy Distutils 的额外功能
-
-
numpy.distutils
的状态和迁移建议-
迁移建议
-
numpy.distutils
与setuptools
的交互
-
-
NumPy C-API
-
Python 类型和 C 结构
-
系统配置
-
数据类型 API
-
数组 API
-
数组迭代器 API
-
通用函数 API
-
广义通用函数 API
-
NumPy 核心库
-
C API 弃用
-
NumPy 的内存管理
-
-
CPU/SIMD 优化
-
CPU 构建选项
-
CPU 调度程序如何工作?
-
-
NumPy 安全性
- 在不受信任的数据上使用 NumPy 的建议
-
NumPy 和 SWIG
-
numpy.i:NumPy 的 SWIG 接口文件
-
测试 numpy.i 类型映射
-
致谢
本手册的大部分内容源自特拉维斯·E·奥利芬特(Travis E. Oliphant)的书籍《NumPy 指南》(https://archive.org/details/NumPyBook)(于 2008 年 8 月慷慨地进入公共领域)。许多函数的参考文档是由众多 NumPy 的贡献者和开发人员编写的。
致谢
本手册的大部分内容来源于 Travis E. Oliphant 的书籍《NumPy 指南》(这本书在 2008 年 8 月慷慨地进入了公有领域)。许多函数的参考文档由 NumPy 的许多贡献者和开发人员编写。
数组对象
NumPy 提供了一个 N 维数组类型,即 ndarray,它描述了相同类型的“项”的集合。这些项可以使用 N 个整数之类的值进行索引。
所有 ndarrays 都是同构的:每个项目占用相同大小的内存块,并且所有块的解释方式完全相同。如何解释数组中的每个项目由一个单独的数据类型对象指定,其中每个数组都关联有一个数据类型对象。除了基本类型(整数、浮点数等),数据类型对象还可以表示数据结构。
通过索引等方式从数组中提取的项目由一个 Python 对象表示,其类型是 NumPy 中内置的数组标量类型之一。数组标量可以轻松操作更复杂的数据排列。
图:概念图展示了描述数组中数据的三个基本对象之间的关系:1)ndarray 本身,2)描述数组中单个固定大小元素布局的数据类型对象,3)当访问数组的单个元素时返回的数组标量 Python 对象。
-
N 维数组(
ndarray
)-
构造数组
-
数组索引
-
ndarray 的内部内存布局
-
数组属性
-
数组方法
-
算术、矩阵乘法和比较操作
-
特殊方法
-
-
标量
-
内置标量类型
-
属性
-
索引
-
方法
-
定义新类型
-
-
数据类型对象(
dtype
)-
指定和构造数据类型
-
dtype
-
-
索引例程
-
生成索引数组
-
类似索引的操作
-
向数组中插入数据
-
数组遍历
-
-
数组遍历
-
单数组迭代
-
广播数组迭代
-
将内循环置于 Cython 中
-
-
标准数组子类
-
特殊属性和方法
-
矩阵对象
-
内存映射文件数组
-
字符数组 (
numpy.char
) -
记录数组 (
numpy.rec
) -
掩码数组 (
numpy.ma
) -
标准容器类
-
数组迭代器
-
-
掩码数组
-
numpy.ma
模块 -
使用 numpy.ma
-
示例
-
numpy.ma
模块的常量 -
MaskedArray
类 -
MaskedArray
方法 -
掩码数组操作
-
-
数组接口协议
-
Python 端
-
C 结构访问
-
类型描述示例
-
与数组接口(版本 2)的差异
-
-
日期时间和时间增量
-
Datetime64 约定和假设
-
基本日期时间
-
日期时间和时间增量算术
-
日期时间单位
-
工作日功能
-
Datetime64 的缺点
-
N 维数组(ndarray
)
ndarray
是一个(通常是固定大小的)相同类型和大小项目的多维容器。数组的维数和项目数由其shape
定义,这是一个指定每个维度大小的非负整数的tuple
。数组中项目的类型由一个单独的数据类型对象(dtype)指定,每个 ndarray 都关联一个数据类型。
与 Python 中的其他容器对象一样,可以通过对数组进行索引或切片(例如使用N个整数)以及通过ndarray
的方法和属性来访问和修改数组的内容。
不同的ndarrays
可以共享相同的数据,因此在一个ndarray
中所做的更改可能在另一个中可见。也就是说,ndarray 可以是另一个 ndarray 的“视图”,它所引用的数据由“基本” ndarray 处理。ndarray 也可以是 Python字符串
或实现buffer
或 array 接口的对象的内存视图。
例子
一个由 4 字节整数元素组成的大小为 2 x 3 的二维数组:
>>> 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
例如,切片可以生成数组的视图:
>>> y = x[:,1]
>>> y
array([2, 5], dtype=int32)
>>> y[0] = 9 # this also changes the corresponding element in x
>>> y
array([9, 5], dtype=int32)
>>> x
array([[1, 9, 3],
[4, 5, 6]], dtype=int32)
构建数组
可以使用 Array creation routines 中详细介绍的例程构建新数组,也可以使用低级ndarray
构造函数:
ndarray (形状[, dtype, buffer, 偏移, ...]) |
数组对象表示固定大小项的多维同类型数组。 |
---|
数组索引
数组可以使用扩展的 Python 切片语法array[selection]
进行索引。类似的语法也用于访问结构化数据类型中的字段。
另请参阅
数组索引。## ndarray 的内部内存布局
一个ndarray
类的实例由计算机内存的连续 1 维段(由数组或其他对象拥有)组成,结合将N个整数映射到块中项目位置的索引方案。索引可以变化的范围由数组的shape
指定。每个项目占用多少字节以及如何解释字节是由与数组相关联的数据类型对象定义的。
内存的一部分本质上是 1 维的,对于N维数组,有许多不同的方案来在 1 维块中排列数组的元素。NumPy 是灵活的,ndarray
对象可以适应任何步进索引方案。在步进方案中,N 维索引((n_0, n_1, ..., n_{N-1})) 对应于偏移量(以字节为单位):
[n_{\mathrm{offset}} = \sum_{k=0}^{N-1} s_k n_k]
从与数组相关联的内存块的开头。这里,(s_k) 是指定数组的strides
的整数。列主序(例如,在 Fortran 语言和Matlab中使用)和行主序(在 C 语言中使用)方案只是特定类型的步进方案,对应的内存可以通过步幅来访问:
[s_k^{\mathrm{column}} = \mathrm{itemsize} \prod_{j=0}^{k-1} d_j , \quad s_k^{\mathrm{row}} = \mathrm{itemsize} \prod_{j=k+1}^{N-1} d_j .]
当 (d_j) = self.shape[j] 时。
C 顺序和 Fortran 顺序都是连续的,即单片段的内存布局,其中内存块的每个部分都可以通过一些索引的组合来访问。
注意
Contiguous arrays 和 single-segment arrays 是同义词,在整个文档中可以互换使用。
虽然 C 风格和 Fortran 风格的连续数组拥有相应的标志位,可以通过上述步幅来访问,但实际步幅可能是不同的。这种情况可能出现在两种情况下:
- 如果
self.shape[k] == 1
,那么对于任何合法的索引index[k] == 0
。这意味着在偏移量的公式中 (n_k = 0),因此 (s_k n_k = 0),而 (s_k) = self.strides[k] 是任意的值。- 如果一个数组没有元素(
self.size == 0
),那么没有合法的索引,步幅也不会被使用。任何没有元素的数组都可以被视为 C 风格和 Fortran 风格的连续数组。
第 1 点意味着 self
和 self.squeeze()
总是具有相同的连续性和 aligned
标志值。这也意味着即使是高维数组也可以同时具有 C 风格和 Fortran 风格的连续性。
如果所有元素的内存偏移和基本偏移本身是* self.itemsize的倍数,则认为数组是对齐的。了解内存对齐*可以在大多数硬件上获得更好的性能。
警告
对于 C 风格连续数组,通常不成立self.strides[-1] == self.itemsize
或者对于 Fortran 风格连续数组self.strides[0] == self.itemsize
。
NPY_RELAXED_STRIDES_DEBUG=1
可用于帮助找到在 C 扩展代码中错误地依赖步幅时的错误(见下面的警告)。
新ndarrays
中的数据按行主序(C)存储,除非另有规定,但是,例如,基本数组切片通常会产生不同方案的视图。
注意
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 |
数组上的一维迭代器。 |
数组接口
另请参阅
数组接口协议.
__array_interface__ |
数组接口的 Python 端 |
---|---|
__array_struct__ |
数组接口的 C 端 |
ctypes
外部函数接口
| ndarray.ctypes
| 简化数组与 ctypes 模块交互的对象。 | ## 数组方法
一个ndarray
对象有许多方法,这些方法以某种方式在数组上操作或与数组一起操作,通常返回一个数组结果。以下简要解释了这些方法。(每个方法的文档字符串中有更完整的描述。)
对于以下方法,numpy
中也有相应的函数:all
, any
, argmax
, argmin
, argpartition
, argsort
, choose
, clip
, compress
, copy
, cumprod
, cumsum
, diagonal
, imag
, max
, mean
, min
, nonzero
, partition
, prod
, ptp
, put
, ravel
, real
, repeat
, reshape
, round
, searchsorted
, sort
, squeeze
, std
, sum
, swapaxes
, take
, trace
, transpose
, var
.
数组转换
ndarray.item (*args) |
将数组中的一个元素复制到标准的 Python 标量并返回。 |
---|---|
ndarray.tolist () |
将数组作为一个a.ndim 级别深度嵌套的 Python 标量列表返回。 |
ndarray.itemset (*args) |
将标量插入数组(如果可能的话,将标量转换为数组的数据类型) |
ndarray.tostring ([order]) |
tobytes 的兼容别名,具有完全相同的行为。 |
ndarray.tobytes ([order]) |
构造包含数组中原始数据字节的 Python 字节。 |
ndarray.tofile (fid[, sep, format]) |
将数组以文本或二进制形式写入文件(默认为二进制)。 |
ndarray.dump (file) |
将数组的 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]) |
分别设置数组标志 WRITEABLE、ALIGNED、WRITEBACKIFCOPY。 |
ndarray.fill (value) |
用标量值填充数组。 |
Shape manipulation
对于 reshape、resize 和 transpose,可以用 n
个整数替换单个元组参数,这将被解释为一个 n-元组。
ndarray.reshape (shape[, order]) |
返回包含相同数据的新形状的数组。 |
---|---|
ndarray.resize (new_shape[, refcheck]) |
在原地改变数组的形状和大小。 |
ndarray.transpose (*axes) |
返回具有转置轴的数组的视图。 |
ndarray.swapaxes (axis1, axis2) |
返回数组的axis1和axis2交换的视图。 |
ndarray.flatten ([order]) |
返回折叠为一维的数组的副本。 |
ndarray.ravel ([order]) |
返回一个扁平化的数组。 |
ndarray.squeeze ([axis]) |
从a中删除长度为一的轴。 |
项目选择和操作
对于带有axis关键字的数组方法,默认为None。如果axis为None,则数组被视为一维数组。axis的任何其他值代表应该进行操作的维度。
ndarray.take (indices[, axis, out, mode]) |
返回由给定索引处的a的元素组成的数组。 |
---|---|
ndarray.put (indices, values[, mode]) |
对所有indices中的n,设置a.flat[n] = values[n] 。 |
ndarray.repeat (repeats[, axis]) |
重复数组的元素。 |
ndarray.choose (choices[, 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]) |
找到应将 v 的元素插入 a 以保持顺序的索引。 |
ndarray.nonzero () |
返回非零元素的索引。 |
ndarray.compress (condition[, axis, out]) |
返回沿着给定轴选择的此数组的切片。 |
ndarray.diagonal ([offset, axis1, axis2]) |
返回指定的对角线。 |
计算
许多方法都带有名为 axis 的参数。在这种情况下,
-
如果 axis 是 None(默认值),则数组被视为 1-D 数组,并且操作在整个数组上执行。如果 self 是 0 维数组或数组标量,则此行为也是默认值。 (数组标量是 float32、float64 等类型/类的实例,而 0 维数组是包含恰好一个数组标量的 ndarray 实例。)
-
如果 axis 是整数,则操作在给定轴上完成(对于可以沿给定轴创建的每个 1-D 子数组)。
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]]))
参数 dtype 指定应该对其进行缩减操作(如求和)的数据类型。默认减少数据类型与 self 的数据类型相同。 为了避免溢出,执行较大数据类型的计算减少可能是有用的。
对于几种方法,还可以提供可选的 out 参数,并且结果将放入给定的输出数组中。 out 参数必须是一个ndarray
,并且具有相同数量的元素。 它可以具有不同的数据类型,在这种情况下将执行强制转换。
ndarray.max ([axis, out, keepdims, initial, ...]) |
返回沿给定轴的最大值。 |
---|---|
ndarray.argmax ([axis, out, keepdims]) |
返回沿给定轴的最大值的索引。 |
ndarray.min ([axis, out, keepdims, initial, ...]) |
返回沿给定轴的最小值。 |
ndarray.argmin ([axis, out, keepdims]) |
返回沿给定轴的最小值的索引。 |
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的任何元素求值为 True,则返回 True。 |
算术运算、矩阵乘法和比较操作
在ndarrays
上的算术和比较运算被定义为逐元素操作,并且通常产生ndarray
对象作为结果。
每个算术运算(+
, -
, *
, /
, //
, %
, divmod()
, **
or pow()
, <<
, >>
, &
, ^
, |
, ~
) 和比较(==
, <
, >
, <=
, >=
, !=
) 都等同于 NumPy 中对应的通用函数(或简称 ufunc)。更多信息,请参阅通用函数部分。
比较运算符:
ndarray.__lt__ (value, /) |
返回 self<value。 |
---|---|
ndarray.__le__ (value, /) |
返回 self<=value。 |
ndarray.__gt__ (value, /) |
返回 self>value。 |
ndarray.__ge__ (value, /) |
返回 self>=value。 |
ndarray.__eq__ (value, /) |
返回 self==value。 |
ndarray.__ne__ (value, /) |
返回 self!=value。 |
数组的布尔值(bool()
):
ndarray.__bool__ (/) |
如果 self 为真,则为真,否则为假。 |
---|
注意
对数组的真值测试调用ndarray.__bool__
,如果数组中的元素数量大于 1,会引发错误,因为这些数组的真值是不明确的。在这种情况下,应该使用.any()
和.all()
来明确表示意思(如果元素的数量为 0,则数组的值为False
)。
一��操作:
ndarray.__neg__ (/) |
-self |
---|---|
ndarray.__pos__ (/) |
+self |
ndarray.__abs__ (self) |
|
ndarray.__invert__ (/) |
~self |
算术运算:
ndarray.__add__ (value, /) |
返回 self+value。 |
---|---|
ndarray.__sub__ (value, /) |
返回 self-value。 |
ndarray.__mul__ (value, /) |
返回 self*value。 |
ndarray.__truediv__ (value, /) |
返回 self/value。 |
ndarray.__floordiv__ (value, /) |
返回 self//value。 |
ndarray.__mod__ (value, /) |
返回 self%value。 |
ndarray.__divmod__ (value, /) |
返回 divmod(self, value)。 |
ndarray.__pow__ (value[, mod]) |
返回 pow(self, value, mod)。 |
ndarray.__lshift__ (value, /) |
返回 self<<value。 |
ndarray.__rshift__ (value, /) |
返回 self>>value。 |
ndarray.__and__ (value, /) |
返回 self&value。 |
ndarray.__or__ (value, /) |
返回 self∣value。 |
ndarray.__xor__ (value, /) |
返回 self^value。 |
注意
-
pow
的第三个参数被悄悄忽略,因为底层的ufunc
只接受两个参数。 -
因为
ndarray
是一个内置类型(用 C 编写),__r{op}__
特殊方法不是直接定义的。 -
通过使用
__array_ufunc__
可以修改为数组实现许多算术特殊方法的函数。
算术,原地:
ndarray.__iadd__ (value, /) |
返回 self+=value。 |
---|---|
ndarray.__isub__ (value, /) |
返回 self-=value。 |
ndarray.__imul__ (value, /) |
返回 self*=value。 |
ndarray.__itruediv__ (value, /) |
返回 self/=value。 |
ndarray.__ifloordiv__ (value, /) |
返回 self//=value。 |
ndarray.__imod__ (value, /) |
返回 self%=value。 |
ndarray.__ipow__ (value, /) |
返回 self**=value。 |
ndarray.__ilshift__ (value, /) |
返回 self<<=value。 |
ndarray.__irshift__ (value, /) |
返回 self>>=value。 |
ndarray.__iand__ (value, /) |
返回 self&=value。 |
ndarray.__ior__ (value, /) |
返回 self|=value。 |
ndarray.__ixor__ (value, /) |
返回 self^=value。 |
警告
原地操作将使用由两个操作数的数据类型决定的精度进行计算,但会悄然将结果降级(如果需要),以便它可以适合回到数组中。因此,对于混合精度计算,A {op}= B
可以不同于 A = A {op} B
。例如,假设 a = ones((3,3))
。然后,a += 3j
不同于 a = a + 3j
:虽然它们都执行相同的计算,a += 3
将结果转换为适合a
,而a = a + 3j
重新绑定名称a
到结果。
矩阵乘法:
ndarray.__matmul__ (value, /) |
返回 self@value。 |
---|
注意
矩阵运算符 @
和 @=
是在 Python 3.5 中遵循 PEP 465引入的,并且 @
运算符已在 NumPy 1.10.0 中引入。更多信息可以在 matmul
文档中找到。
特殊方法
对于标准库函数:
ndarray.__copy__ () |
如果在数组上调用 copy.copy 时使用。 |
---|---|
ndarray.__deepcopy__ (memo, /) |
如果在数组上调用copy.deepcopy 时使用。 |
ndarray.__reduce__ () |
用于 pickle。 |
ndarray.__setstate__ (state, /) |
用于取消 pickle。 |
基本自定义:
ndarray.__new__ (*args, **kwargs) |
|
---|---|
ndarray.__array__ ([dtype], /) |
如果未给出 dtype,则返回对自身的新引用;如果 dtype 与数组的当前 dtype 不同,则返回提供的数据类型的新数组。 |
ndarray.__array_wrap__ (array[, context], /) |
返回与 self 相同类型的数组array 的视图。 |
容器定制:(参见索引)
ndarray.__len__ (/) |
返回 self 的长度。 |
---|---|
ndarray.__getitem__ (key, /) |
返回 self[key]。 |
ndarray.__setitem__ (key, value, /) |
将 self[key] 设置为 value。 |
ndarray.__contains__ (key, /) |
返回 key 是否在 self 中。 |
转换;操作int()
、float()
和complex()
。它们仅适用于具有一个元素的数组,并返回适当的标量。
ndarray.__int__ (self) |
|
---|---|
ndarray.__float__ (self) |
|
ndarray.__complex__ |
字符串表示:
ndarray.__str__ (/) |
返回 str(self)。 |
---|---|
ndarray.__repr__ (/) |
返回 repr(self)。 |
输入数组的实用方法:
ndarray.__class_getitem__ (item, /) |
返回围绕ndarray 类型的参数化包装器。 |
---|
构建数组
可以使用数组创建例程中详细描述的例程构建新数组,也可以使用低级别的ndarray
构造器:
ndarray (shape[, dtype, buffer, offset, ...]) |
数组对象表示具有固定大小项的多维同构数组。 |
---|
数组索引
可以使用扩展的 Python 切片语法 array[selection]
对数组进行索引。类似的语法也用于访问结构化数据类型中的字段。
另请参见
数组索引。
ndarray 的内部内存布局
ndarray
类的一个实例由计算机内存中的一段连续的一维区段(由数组所拥有,或由其他对象拥有)以及将 N 个整数映射到区块中条目位置的索引方案组成。索引范围由数组的 shape
指定。每个条目占用多少字节以及这些字节如何解释由与数组关联的 数据类型对象 定义。
内存段本质上是一维的,有许多不同的方案可以将 N 维数组的条目排列在一维块中。NumPy 是灵活的,ndarray
对象可以适应任何跨步索引方案。在跨步方案中,N 维索引 ((n_0, n_1, ..., n_{N-1})) 对应于偏移量(以字节表示):
[n_{\mathrm{偏移量}} = \sum_{k=0}^{N-1} s_k n_k]
从与数组关联的内存块的起始位置开始计算。这里,(s_k) 是指定数组的 strides
的整数。列优先顺序(例如,在 Fortran 语言和* Matlab 中使用)和行优先顺序(在 C 中使用)方案只是特定类型的跨步方案,并且对应于可以通过跨步寻址*的内存:
[s_k^{\mathrm{列}} = \mathrm{itemsize} \prod_{j=0}^{k-1} d_j , \quad s_k^{\mathrm{行}} = \mathrm{itemsize} \prod_{j=k+1}^{N-1} d_j .]
这里的 (d_j) = self.shape[j]。
C 和 Fortran 顺序都是连续,即单一段,内存布局,其中内存块的每个部分都可以通过某种结合的索引访问。
注意
连续数组 和 单一段数组 是同义词,文档中可以互换使用。
尽管 C 风格和 Fortran 风格的连续数组具有相应的标志设置,可以通过上述步幅进行寻址,但实际的步幅可能不同。这种情况可能发生在两种情况下:
- 如果
self.shape[k] == 1
,则对于任何合法索引index[k] == 0
。这意味着在偏移量的公式中 (n_k = 0),因此 (s_k n_k = 0),而 (s_k) 的值 = self.strides[k] 是任意的。- 如果一个数组没有元素(
self.size == 0
),则没有合法的索引,步幅永远不会被使用。任何没有元素的数组都可以被认为是 C 风格和 Fortran 风格连续的。
点 1.表示self
和self.squeeze()
始终具有相同的连续性和aligned
标志值。这也意味着即使是高维数组在同一时间也可以是 C 风格和 Fortran 风格连续的。
如果所有元素的内存偏移和基本偏移本身都是* self.itemsize的倍数,那么数组被视为对齐。了解内存对齐*可在大多数硬件上获得更好的性能。
警告
一般而言,并不总是成立self.strides[-1] == self.itemsize
对于 C 风格连续数组或self.strides[0] == self.itemsize
对于 Fortran 风格连续数组是正确的。
可以使用NPY_RELAXED_STRIDES_DEBUG=1
来帮助找到在 C 扩展代码中错误依赖步幅时的错误(见下面的警告)。
新建的ndarrays
中的数据是按照行主序(C)顺序排列,除非另有指定,但例如,基本数组切片通常会产生不同方案的视图。
注意
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 |
数组的一维迭代器。 |
数组接口
另请参见
数组接口协议。
__array_interface__ |
数组接口的 Python 部分 |
---|---|
__array_struct__ |
数组接口的 C 部分 |
ctypes
外部函数接口
ndarray.ctypes |
用于简化数组与 ctypes 模块交互的对象。 |
---|
内存布局
以下属性包含有关数组内存布局的信息:
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 |
数组上的 1-D 迭代器。 |
数组接口
另请参见
数组接口协议。
__array_interface__ |
数组接口的 Python 端 |
---|---|
__array_struct__ |
数组接口的 C 端 |
ctypes
外部函数接口
ndarray.ctypes |
简化数组与 ctypes 模块交互的对象。 |
---|
数组方法
一个ndarray
对象具有许多操作数组的方法,通常以某种方式返回数组结果。以下简要解释了这些方法(每个方法的文档字符串有更完整的描述)。
对于下面的方法,numpy
中也有对应的函数:all
, any
, argmax
, argmin
, argpartition
, argsort
, choose
, clip
, compress
, copy
, cumprod
, cumsum
, diagonal
, imag
, max
, mean
, min
, nonzero
, partition
, prod
, ptp
, put
, ravel
, real
, repeat
, reshape
, round
, searchsorted
, sort
, squeeze
, std
, sum
, swapaxes
, take
, trace
, transpose
, var
.
数组转换
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 (file) |
将数组的 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]) |
设置数组标志,分别为 WRITEABLE,ALIGNED,WRITEBACKIFCOPY。 |
ndarray.fill (value) |
用标量值填充数组。 |
形状操作
对于 reshape,resize 和 transpose,单个元组参数可以由n
个整数代替,这将被解释为 n 元组。
ndarray.reshape (shape[, order]) |
返回包含相同数据且具有新形状的数组。 |
---|---|
ndarray.resize (new_shape[, refcheck]) |
在原地改变数组的形状和大小。 |
ndarray.transpose (*axes) |
返回数组的轴转置。 |
ndarray.swapaxes (axis1, axis2) |
返回数组的视图,其中 axis1 和 axis2 互换。 |
ndarray.flatten ([order]) |
返回折叠为一维的数组副本。 |
ndarray.ravel ([order]) |
返回展平的数组。 |
ndarray.squeeze ([axis]) |
从 a 中删除长度为一的轴。 |
项目选择和操作
对于带有 axis 关键字的数组方法,默认为 None。如果 axis 为 None,则将数组视为 1-D 数组。axis 的任何其他值表示应沿其进行操作的维度。
ndarray.take (indices[, axis, out, mode]) |
返回由给定索引处的 a 元素组成的数组。 |
---|---|
ndarray.put (indices, values[, mode]) |
对于索引中的所有 n,设置 a.flat[n] = values[n] 。 |
ndarray.repeat (repeats[, axis]) |
重复数组的元素。 |
ndarray.choose (choices[, 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]) |
找到应将 v 的元素插入 a 中以保持顺序的索引。 |
ndarray.nonzero () |
返回非零元素的索引。 |
ndarray.compress (condition[, axis, out]) |
返回沿给定轴选择的该数组的切片。 |
ndarray.diagonal ([offset, axis1, axis2]) |
返回指定的对角线。 |
计算
许多这些方法都有名为axis的参数。在这种情况下,
-
如果axis是None(默认值),则数组被视为 1-D 数组,并且该操作是在整个数组上执行的。 如果 self 是 0 维数组或数组标量,此行为也是默认值。 (数组标量是 types/classes float32,float64 等的实例,而 0 维数组是包含精确一个数组标量的 ndarray 实例。)
-
如果axis是一个整数,则操作是沿着给定的轴进行的(对于可以沿着给定轴创建的每个 1-D 子数组)。
axis参数的示例
一个尺寸为 3 x 3 x 3 的 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]]))
参数dtype指定应在其上执行缩减操作(如求和)的数据类型。 默认缩减数据类型与self的数据类型相同。 为了避免溢出,使用更大的数据类型执行缩减操作可能很有用。
对于一些方法,还可以提供可选的out参数,并将结果放入给定的输出数组中。 out参数必须是一个ndarray
,并且具有相同数量的元素。 它可以具有不同的数据类型,在这种情况下将执行强制转换。
ndarray.max ([axis, out, keepdims, initial, ...]) |
返回给定轴上的最大值。 |
---|---|
ndarray.argmax ([axis, out, keepdims]) |
返回沿给定轴的最大值的索引。 |
ndarray.min ([axis, out, keepdims, initial, ...]) |
返回给定轴上的最小值。 |
ndarray.argmin ([axis, out, keepdims]) |
返回沿给定轴的最小值的索引。 |
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的任何元素评估为 True,则返回 True。 |
数组转换
ndarray.item (*args) |
将数组的元素复制到标准 Python 标量并返回它。 |
---|---|
ndarray.tolist () |
将数组作为 Python 标量的a.ndim 级别深度的嵌套列表返回。 |
ndarray.itemset (*args) |
将标量插入到数组中(如可能,将标量转换为数组的 dtype) |
ndarray.tostring ([order]) |
一个与tobytes完全相同行为的兼容别名。 |
ndarray.tobytes ([order]) |
构造包含数组中原始数据字节的 Python 字节。 |
ndarray.tofile (fid[, sep, format]) |
将数组作为文本或二进制(默认)写入文件。 |
ndarray.dump (file) |
将数组的 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]) |
设置数组标志 WRITEABLE, ALIGNED, WRITEBACKIFCOPY。 |
ndarray.fill (value) |
使用标量值填充数组。 |
形状操作
对于 reshape、resize 和 transpose,可以用n
个整数替换单个元组参数,它们将被解释为一个 n 元组。
ndarray.reshape (shape[, order]) |
返回包含相同数据的数组的新形状。 |
---|---|
ndarray.resize (new_shape[, refcheck]) |
在原地更改数组的形状和大小。 |
ndarray.transpose (*axes) |
返回按轴置换的数组的视图。 |
ndarray.swapaxes (axis1, axis2) |
返回axis1和axis2互换的数组的视图。 |
ndarray.flatten ([order]) |
返回压缩为一维的数组副本。 |
ndarray.ravel ([order]) |
返回一个扁平化的数组。 |
ndarray.squeeze ([axis]) |
从a中删除长度为 1 的轴。 |
项目选择和操作
对于带有axis关键字的数组方法,默认值为None。如果axis为None,则将数组视为 1-D 数组。对于axis的任何其他值表示应该进行操作的维度。
ndarray.take (indices[, axis, out, mode]) |
返回从给定索引处的元素形成的数组。 |
---|---|
ndarray.put (indices, values[, mode]) |
对所有indices中的n设置a.flat[n] = values[n] 。 |
ndarray.repeat (repeats[, axis]) |
重复数组的元素。 |
ndarray.choose (choices[, out, mode]) |
使用索引数组从一组选择中构造一个新数组。 |
ndarray.sort ([axis, kind, order]) |
就地对数组进行排序。 |
ndarray.argsort ([axis, kind, order]) |
返回按排序数组的索引。 |
ndarray.partition (kth[, axis, kind, order]) |
以使数组中第 kth 位置的元素值处于排序数组中的位置的方式重新排列数组中的元素。 |
ndarray.argpartition (kth[, axis, kind, order]) |
返回将此数组划分的索引。 |
ndarray.searchsorted (v[, side, sorter]) |
找到元素的插入位置以维持顺序。 |
ndarray.nonzero () |
返回非零元素的索引。 |
ndarray.compress (condition[, axis, out]) |
返回沿指定轴选择的该数组的切片。 |
ndarray.diagonal ([offset, axis1, axis2]) |
返回指定的对角线。 |
计算
这些方法中许多方法都接受名为axis的参数。在这种情况下,
-
如果axis是None(默认值),则将数组视为一维数组,并在整个数组上执行操作。如果 self 是 0 维数组或数组标量,则此行为也是默认行为。(数组标量是 float32、float64 等类型/类的实例,而 0 维数组是包含一个数组标量的 ndarray 实例。)
-
如果axis是整数,则对给定轴进行操作(对可以沿给定轴创建的每个 1 维子数组进行操作)。
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]]))
参数dtype指定应在其上进行缩减操作(如求和)的数据类型。默认缩减数据类型与self的数据类型相同。为避免溢出,执行缩减时使用较大的数据类型可能会很有用。
对于几种方法,还可以提供一个可选的out参数,并将结果放入给定的输出数组中。out参数必须是一个ndarray
,并且具有相同数量的元素。它可以具有不同的数据类型,这种情况下会执行强转换。
ndarray.max ([axis, out, keepdims, initial, ...]) |
返回沿指定轴的最大值。 |
---|---|
ndarray.argmax ([axis, out, keepdims]) |
返回沿指定轴的最大值的索引。 |
ndarray.min ([axis, out, keepdims, initial, ...]) |
返回沿指定轴的最小值。 |
ndarray.argmin ([axis, out, keepdims]) |
返回沿指定轴的最小值的索引。 |
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的任何元素求值为 True,则返回 True。 |
算术,矩阵乘法和比较操作
对ndarrays
上的算术和比较操作被定义为逐元素操作,并通常产生ndarray
对象作为结果。
每个算术操作(+
, -
, *
, /
, //
, %
, divmod()
, **
或pow()
, <<
, >>
, &
, ^
, |
, ~
)和比较(==
, <
, >
, <=
, >=
, !=
)都等同于 NumPy 中相应的通用函数(或 ufunc)。更多信息,请参见通用函数部分。
比较运算符:
ndarray.__lt__ (value, /) |
返回 self<value。 |
---|---|
ndarray.__le__ (value, /) |
返回 self<=value。 |
ndarray.__gt__ (value, /) |
返回 self>value。 |
ndarray.__ge__ (value, /) |
返回 self>=value。 |
ndarray.__eq__ (value, /) |
返回 self==value。 |
ndarray.__ne__ (value, /) |
返回 self!=value。 |
数组的真值(bool()
):
ndarray.__bool__ (/) |
如果 self 为真则返回 True,否则返回 False |
---|
注意
对数组进行真值测试时会调用 ndarray.__bool__
,如果数组中的元素数量大于 1,则会引发错误,因为这种情况下数组的真值是不确定的。可以使用.any()
和.all()
来明确表示在这种情况下的意思。(如果元素数量为 0,则数组的值为False
。)
一元操作:
ndarray.__neg__ (/) |
-self |
---|---|
ndarray.__pos__ (/) |
+self |
ndarray.__abs__ (self) |
|
ndarray.__invert__ (/) |
~self |
算术运算:
ndarray.__add__ (value, /) |
返回 self+value。 |
---|---|
ndarray.__sub__ (value, /) |
返回 self-value。 |
ndarray.__mul__ (value, /) |
返回 self*value。 |
ndarray.__truediv__ (value, /) |
返回 self/value。 |
ndarray.__floordiv__ (value, /) |
返回 self//value。 |
ndarray.__mod__ (value, /) |
返回 self%value。 |
ndarray.__divmod__ (value, /) |
返回 divmod(self, value)。 |
ndarray.__pow__ (value[, mod]) |
返回 pow(self, value, mod)。 |
ndarray.__lshift__ (value, /) |
返回 self<<value。 |
ndarray.__rshift__ (value, /) |
返回 self>>value。 |
ndarray.__and__ (value, /) |
返回 self&value。 |
ndarray.__or__ (value, /) |
返回 self|value。 |
ndarray.__xor__ (value, /) |
返回 self^value。 |
注意
-
pow
的第三个参数被默默忽略,因为底层的ufunc
只接受两个参数。 -
因为
ndarray
是一个内置类型(用 C 编写),因此直接定义了__r{op}__
特殊方法。 -
通过使用
__array_ufunc__
,可以修改数组的许多算术特殊方法调用的函数。
算术,就地运算:
ndarray.__iadd__ (value, /) |
返回 self+=value。 |
---|---|
ndarray.__isub__ (value, /) |
返回 self-=value。 |
ndarray.__imul__ (value, /) |
返回 self*=value。 |
ndarray.__itruediv__ (value, /) |
返回 self/=value。 |
ndarray.__ifloordiv__ (value, /) |
返回 self//=value。 |
ndarray.__imod__ (value, /) |
返回 self%=value。 |
ndarray.__ipow__ (value, /) |
返回 self**=value。 |
ndarray.__ilshift__ (value, /) |
返回 self<<=value。 |
ndarray.__irshift__ (value, /) |
返回 self>>=value。 |
ndarray.__iand__ (value, /) |
返回 self&=value。 |
ndarray.__ior__ (value, /) |
返回 self|=value。 |
ndarray.__ixor__ (value, /) |
返回 self^=value。 |
警告
原地操作将使用两个操作数的数据类型决定的精度执行计算,但会默默地降级结果(如果必要的话),以便它可以适合数组。因此,对于混合精度计算,A {op}= B
可能与A = A {op} B
不同。例如,假设a = ones((3,3))
。那么,a += 3j
与a = a + 3j
不同:虽然它们都执行相同的计算,a += 3
将结果转换为适合a
,而a = a + 3j
会将名称a
重新绑定到结果。
矩阵乘法:
ndarray.__matmul__ (value, /) |
返回 self@value。 |
---|
注意
在 Python 3.5 中引入了矩阵运算符@
和@=
,遵循了PEP 465,而@
操作符在 NumPy 1.10.0 中被引入。更多信息可以在matmul
文档中找到。
特殊方法
对于标准库函数:
ndarray.__copy__ () |
如果在数组上调用copy.copy 时使用。 |
---|---|
ndarray.__deepcopy__ (memo, /) |
如果在数组上调用copy.deepcopy 时使用。 |
ndarray.__reduce__ () |
用于 pickle。 |
ndarray.__setstate__ (state, /) |
用于取消 pickle。 |
基本定制:
ndarray.__new__ (*args, **kwargs) |
|
---|---|
ndarray.__array__ ([dtype], /) |
如果未提供 dtype,则返回对 self 的新引用,如果 dtype 与数组的当前 dtype 不同,则返回提供的数据类型的新数组。 |
ndarray.__array_wrap__ (array[, context], /) |
返回与 self 相同类型的array 的视图。 |
容器定制:(参见 Indexing)
ndarray.__len__ (/) |
返回 self 的长度。 |
---|---|
ndarray.__getitem__ (key, /) |
返回 self[key]。 |
ndarray.__setitem__ (key, value, /) |
将 self[key] 设置为 value。 |
ndarray.__contains__ (key, /) |
返回 key 是否在 self 中。 |
转换; 操作 int()
, float()
和 complex()
。它们仅适用于只有一个元素的数组,并返回相应的标量。
ndarray.__int__ (self) |
|
---|---|
ndarray.__float__ (self) |
|
ndarray.__complex__ |
字符串表示:
ndarray.__str__ (/) |
返回 str(self)。 |
---|---|
ndarray.__repr__ (/) |
返回 repr(self)。 |
类型的实用方法:
ndarray.__class_getitem__ (item, /) |
返回 ndarray 类型的参数化包装器。 |
---|
numpy.ndarray
class numpy.ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)
一个数组对象表示固定大小项的多维、同构数组。一个关联的数据类型对象描述了数组中每个元素的格式(它的字节顺序、它在内存中占用多少字节、它是整数、浮点数还是其他内容等等)。
数组应该使用 array
、zeros
或 empty
来构造(请参阅下面的参考部分)。这里给出的参数指的是用于实例化数组的低级方法(*ndarray(…))。
更多信息,请参考 numpy
模块并检查数组的方法和属性。
参数:
(对于 new 方法;看下面的注意)**
shape 一组整数
创建数组的形状。
dtype 数据类型,可选
任何可以被解释为 numpy 数据类型的对象。
buffer 暴露缓冲区接口的对象,可选
用于用数据填充数组。
offset 整数,可选
数组数据在缓冲区中的偏移量。
strides 一组整数,可选
内存中数据的步幅。
order,可选
行主要(C 风格)或列主要(Fortran 风格)顺序。
参见
array
构造一个数组。
zeros
创建一个每个元素都为零的数组。
empty
创建一个数组,但不改变其已分配的内存(也就是说,它包含“垃圾”)。
dtype
创建数据类型。
numpy.typing.NDArray
一个关于其 dtype.type
的别名的 ndarray 泛型。
注意事项
有两种使用 __new__
创建数组的模式:
-
如果 buffer 为 None,则只使用
shape
、dtype
和 order。 -
如果 buffer 是一个暴露缓冲区接口的对象,则所有关键字都会被解释。
不需要 __init__
方法,因为在 __new__
方法之后数组已完全初始化。
例子
这些示例说明了使用底层 ndarray
构造函数。请参考上面的 参考 部分以了解更简单的构建 ndarray 的方法。
第一种模式,buffer 为 None:
>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
[ nan, 2.5e-323]])
第二种模式:
>>> np.ndarray((2,), buffer=np.array([1,2,3]),
... offset=np.int_().itemsize,
... dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])
属性:
T
ndarray
转置数组的视图。
data
缓冲区
指向数组数据起始位置的 Python 缓冲区对象。
dtype
dtype 对象
数组元素的数据类型。
flags
dict
数组的内存布局信息。
flat
numpy.flatiter 对象
数组的一维迭代器。
imag
ndarray
数组的虚部。
real
ndarray
数组的实部。
size
int
数组中的元素数。
itemsize
int
一个数组元素的字节数。
nbytes
int
数组元素所消耗的总字节数。
ndim
int
数组的维度数。
shape
int 元组
数组的维度的元组。
strides
int 元组
在遍历数组时在每个维度中步进的字节数元组。
ctypes
ctypes 对象
一个简化数组与 ctypes 模块交互的对象。
base
ndarray
如果内存来自其他对象,则是基础对象。
方法
all ([axis, out, keepdims, where]) |
如果所有元素均为 True,则返回 True。 |
---|---|
any ([axis, out, keepdims, where]) |
如果 a 中的任何元素为 True,则返回 True。 |
argmax ([axis, out, keepdims]) |
返回沿给定轴的最大值的索引。 |
argmin ([axis, out, keepdims]) |
返回沿给定轴的最小值的索引。 |
argpartition (kth[, axis, kind, order]) |
返回对数组进行分区的索引。 |
argsort ([axis, kind, order]) |
返回对数组进行排序的索引。 |
astype (dtype[, order, casting, subok, copy]) |
数组的副本,强制转换为指定的类型。 |
byteswap ([inplace]) |
交换数组元素的字节 |
choose (choices[, out, mode]) |
使用索引数组从一组选择中构建新数组。 |
clip ([min, max, out]) |
返回值限制在 [min, max] 范围内的数组。 |
compress (condition[, axis, out]) |
返回沿给定轴选择的该数组的切片。 |
conj () |
全部元素进行复共轭。 |
conjugate () |
返回复共轭,逐元素。 |
copy ([order]) |
返回数组的副本。 |
cumprod ([axis, dtype, out]) |
返回沿给定轴的元素的累积乘积。 |
cumsum ([axis, dtype, out]) |
返回沿给定轴的元素的累积和。 |
diagonal ([offset, axis1, axis2]) |
返回指定的对角线。 |
dump (file) |
将数组的 pickle 格式存储到指定文件。 |
dumps () |
将数组的 pickle 格式作为字符串返回。 |
fill (value) |
用标量值填充数组。 |
flatten ([order]) |
返回将数组展平为一维的副本。 |
getfield (dtype[, offset]) |
返回给定数组的某个字段为特定类型。 |
item (*args) |
将数组的元素复制到标准 Python 标量并返回。 |
itemset (*args) |
将标量插入数组(如果可能,将标量转换为数组的数据类型) |
max ([axis, out, keepdims, initial, where]) |
返回给定轴上的最大值。 |
mean ([axis, dtype, out, keepdims, where]) |
返回沿给定轴的数组元素的平均值。 |
min ([axis, out, keepdims, initial, where]) |
返回给定轴上的最小值。 |
newbyteorder ([new_order]) |
使用不同的字节顺序返回相同数据的数组。 |
nonzero () |
返回非零元素的索引。 |
partition (kth[, axis, kind, order]) |
重新排列数组中的元素,使得第 k 个位置的元素值在排序后的数组中所处的位置。 |
prod ([axis, dtype, out, keepdims, initial, ...]) |
返回给定轴上数组元素的乘积。 |
ptp ([axis, out, keepdims]) |
沿指定轴的峰值至峰值(最大值 - 最小值)。 |
put (indices, values[, mode]) |
对所有* n *中的a.flat[n] = values[n] 进行设置,其中 n 为索引。 |
ravel ([order]) |
返回一个扁平化的数组。 |
repeat (repeats[, axis]) |
重复数组的元素。 |
reshape (shape[, order]) |
返回一个包含相同数据的新形状数组。 |
resize (new_shape[, refcheck]) |
在原地改变数组的形状和大小。 |
round ([decimals, out]) |
返回* a *中每个元素舍入到给定小数位数。 |
searchsorted (v[, side, sorter]) |
找到应该插入 v 中的元素在 a 中保持顺序的索引位置。 |
setfield (val, dtype[, offset]) |
将一个值放入由数据类型定义的字段的指定位置。 |
setflags ([write, align, uic]) |
设置数组标志可写,对齐,WRITEBACKIFCOPY 分别。 |
sort ([axis, kind, order]) |
原地对数组进行排序。 |
squeeze ([axis]) |
从a中删除长度为一的轴。 |
std ([axis, dtype, out, ddof, keepdims, where]) |
返回沿给定轴的数组元素的标准差。 |
sum ([axis, dtype, out, keepdims, initial, where]) |
返回沿给定轴的数组元素的和。 |
swapaxes (axis1, axis2) |
返回数组的视图,交换axis1和axis2。 |
take (indices[, axis, out, mode]) |
返回一个由a给定索引处元素组成的数组。 |
tobytes ([order]) |
构造包含数组中原始数据字节的 Python 字节。 |
tofile (fid[, sep, format]) |
将数组以文本或二进制(默认)形式写入文件。 |
tolist () |
将数组作为一个a.ndim 级别深的 Python 标量嵌套列表返回。 |
tostring ([order]) |
tobytes 的兼容别名,具有完全相同的行为。 |
trace ([offset, axis1, axis2, dtype, out]) |
返回数组对角线上的和。 |
transpose (*axes) |
返回数组的轴转置视图。 |
var ([axis, dtype, out, ddof, keepdims, where]) |
返回数组元素沿着给定轴的方差。 |
view ([dtype][, type]) |
以相同数据创建数组的新视图。 |
dot |
numpy.ndarray.flags
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.flags.html
属性
ndarray.flags
数组的内存布局信息。
注意事项
flags
对象可以像字典一样访问(如a.flags['WRITEABLE']
),也可以使用小写属性名称(如a.flags.writeable
)。只支持字典访问的短标志名称。
只能通过直接分配给属性或字典条目,或通过调用ndarray.setflags
来更改 WRITEBACKIFCOPY、WRITEABLE 和 ALIGNED 标志。
数组的标志不能随意设置:
-
WRITEBACKIFCOPY 只能设置为
False
。 -
只有数据真正对齐时,ALIGNED 才能设置为
True
。 -
只有当数组拥有自己的内存或内存的最终所有者暴露了可写入的缓冲区接口,或者是一个字符串时,WRITEABLE 才能设置为
True
。
数组可以同时是 C 风格和 Fortran 风格连续的。这对于 1 维数组是清楚的,但对于更高维数组也可能为真。
即使对于连续的数组,对于给定维度arr.strides[dim]
的步幅可能是任意的,如果arr.shape[dim] == 1
或数组没有元素。对于 C 风格连续数组或 Fortran 风格连续数组,通常不成立self.strides[-1] == self.itemsize
(对于 C 风格连续数组)或self.strides[0] == self.itemsize
(对于 Fortran 风格连续数组)。
属性:
C_CONTIGUOUS (C)
数据在一个单一的、符合 C 风格的连续段中。
F_CONTIGUOUS (F)
数据在一个单一的、符合 Fortran 风格的连续段中。
OWNDATA (O)
数组拥有它使用的内存或从另一个对象借用它。
WRITEABLE (W)
数据区域可以被写入。将其设置为 False 会锁定数据,使之为只读。视图(切片等)在创建时从其基础数组继承 WRITEABLE,但对于可写数组的视图可以随后被锁定,而基础数组保持可写。 (相反则不成立,即不能将视图从只读数组改为可写。但是,目前锁定基对象不会锁定已引用它的任何视图,因此在这种情况下,通过之前创建的视图可以更改被锁定数组的内容。)尝试更改不可写数组会引发 RuntimeError 异常。
ALIGNED (A)
数据和所有元素都与硬件适当地对齐。
WRITEBACKIFCOPY (X)
这个数组是另一个数组的副本。在释放内存之前必须调用 C-API 函数 PyArray_ResolveWritebackIfCopy,以便将基础数组更新为此数组的内容。
FNC
F_CONTIGUOUS 而不是 C_CONTIGUOUS。
FORC
F_CONTIGUOUS 或 C_CONTIGUOUS���单一段测试)。
BEHAVED (B)
ALIGNED 和 WRITEABLE。
CARRAY (CA)
BEHAVED 和 C_CONTIGUOUS。
FARRAY (FA)
BEHAVED 和 F_CONTIGUOUS,但不是 C_CONTIGUOUS。
numpy.ndarray.shape
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.shape.html
attribute
ndarray.shape
Tuple of array dimensions.
The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape
, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.
Warning
Setting arr.shape
is discouraged and may be deprecated in the future. Using ndarray.reshape
is the preferred approach.
See also
numpy.shape
Equivalent getter function.
numpy.reshape
Function similar to setting shape
.
ndarray.reshape
Method similar to setting shape
.
Examples
>>> x = np.array([1, 2, 3, 4])
>>> x.shape
(4,)
>>> y = np.zeros((2, 3, 4))
>>> y.shape
(2, 3, 4)
>>> y.shape = (3, 8)
>>> y
array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]])
>>> y.shape = (3, 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: total size of new array must be unchanged
>>> np.zeros((4,2))[::2].shape = (-1,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Incompatible shape for in-place modification. Use
`.reshape()` to make a copy with the desired shape.
numpy.ndarray.strides
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.strides.html
属性
ndarray.strides
在遍历数组时,每个维度步进的字节数元组。
元素(i[0], i[1], ..., i[n])
在数组a中的字节偏移量为:
offset = sum(np.array(i) * a.strides)
在 NumPy 参考指南的“ndarray.rst”文件中可以找到更详细的关于步幅的解释。
警告
设置arr.strides
是不鼓励的,可能会在将来被弃用。应该优先选择numpy.lib.stride_tricks.as_strided
以更安全的方式创建同一数据的新视图。
另请参阅
numpy.lib.stride_tricks.as_strided
注意
想象一个 32 位整数数组(每个 4 个字节):
x = np.array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]], dtype=np.int32)
这个数组以 40 个字节的形式依次存储在内存中(称为连续的内存块)。数组的步幅告诉我们在内存中移动到特定轴上的下一个位置时需要跳过多少字节。例如,我们需要跳过 4 个字节(1 个值)才能移动到下一列,但是要跳过 20 个字节(5 个值)才能到达下一行的相同位置。因此,数组x的步幅将为(20, 4)
。
实例
>>> y = np.reshape(np.arange(2*3*4), (2,3,4))
>>> y
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]]])
>>> y.strides
(48, 16, 4)
>>> y[1,1,1]
17
>>> offset=sum(y.strides * np.array((1,1,1)))
>>> offset/y.itemsize
17
>>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3,5,2,2])
>>> offset = sum(i * x.strides)
>>> x[3,5,2,2]
813
>>> offset / x.itemsize
813
numpy.ndarray.ndim
numpy.org/doc/1.26/reference/generated/numpy.ndarray.ndim.html
属性
ndarray.ndim
数组的维度数量。
示例
>>> x = np.array([1, 2, 3])
>>> x.ndim
1
>>> y = np.zeros((2, 3, 4))
>>> y.ndim
3
numpy.ndarray.data
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.data.html
属性
ndarray.data
指向数组数据起始位置的 Python 缓冲对象。
numpy.ndarray.size
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.size.html
属性
ndarray.size
数组中的元素数量。
等同于np.prod(a.shape)
,即数组维度的乘积。
注意事项
a.size 返回一个标准的任意精度 Python 整数。这在使用其他方法获取相同值时可能不成立(比如建议的np.prod(a.shape)
,它返回一个np.int_
的实例),这在进一步计算中可能会溢出固定大小的整数类型时可能会有影响。
示例
>>> x = np.zeros((3, 5, 2), dtype=np.complex128)
>>> x.size
30
>>> np.prod(x.shape)
30
numpy.ndarray.itemsize
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.itemsize.html
属性
ndarray.itemsize
一个数组元素的长度(以字节为单位)。
示例
>>> x = np.array([1,2,3], dtype=np.float64)
>>> x.itemsize
8
>>> x = np.array([1,2,3], dtype=np.complex128)
>>> x.itemsize
16
numpy.ndarray.nbytes
numpy.org/doc/1.26/reference/generated/numpy.ndarray.nbytes.html
属性
ndarray.nbytes
数组元素所占用的总字节数。
另请参见
对象本身在视图情况下没有父级所占用的内存。这包括非元素属性所占用的内存。
注释
不包括数组对象的非元素属性所占用的内存。
例子
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
>>> np.prod(x.shape) * x.itemsize
480
numpy.ndarray.base
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.base.html
属性
ndarray.base
如果内存来自其他对象,则为基本对象。
示例
拥有自己内存的数组的基本对象为 None:
>>> x = np.array([1,2,3,4])
>>> x.base is None
True
切片创建一个视图,其内存与 x 共享:
>>> y = x[2:]
>>> y.base is x
True
numpy.ndarray.dtype
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.dtype.html
属性
ndarray.dtype
数组元素的数据类型。
警告
不建议设置arr.dtype
,未来可能会弃用。设置会替换dtype
但不修改内存(另请参阅ndarray.view
和ndarray.astype
)。
参数:
None
返回:
dnumpy dtype 对象
另请参阅
ndarray.astype
将数组中包含的值强制转换为新的数据类型。
ndarray.view
创建一个相同数据的视图,但数据类型不同。
numpy.dtype
示例
>>> x
array([[0, 1],
[2, 3]])
>>> x.dtype
dtype('int32')
>>> type(x.dtype)
<type 'numpy.dtype'>
numpy.ndarray.T
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.T.html
属性
ndarray.T
转置数组的视图。
与 self.transpose()
相同。
参见
transpose
例子
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
[3, 4]])
>>> a.T
array([[1, 3],
[2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.T
array([1, 2, 3, 4])
numpy.ndarray.real
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.real.html
属性
ndarray.real
数组的实部。
另请参阅
等效函数
示例
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.real
array([ 1\. , 0.70710678])
>>> x.real.dtype
dtype('float64')
numpy.ndarray.imag
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.imag.html
属性
ndarray.imag
数组的虚部。
示例
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.imag
array([ 0\. , 0.70710678])
>>> x.imag.dtype
dtype('float64')
numpy.ndarray.flat
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.flat.html
属性
ndarray.flat
数组上的一维迭代器。
这是一个numpy.flatiter
实例,表现类似于但不是 Python 内置的迭代器对象的子类。
另见
flatten
返回将数组折叠成一维的副本。
flatiter
示例
>>> x = np.arange(1, 7).reshape(2, 3)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> x.flat[3]
4
>>> x.T
array([[1, 4],
[2, 5],
[3, 6]])
>>> x.T.flat[3]
5
>>> type(x.flat)
<class 'numpy.flatiter'>
一个赋值示例:
>>> x.flat = 3; x
array([[3, 3, 3],
[3, 3, 3]])
>>> x.flat[[1,4]] = 1; x
array([[3, 1, 3],
[3, 1, 3]])
numpy.ndarray.ctypes
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.ctypes.html
属性
ndarray.ctypes
一个简化数组与 ctypes 模块交互的对象。
这个属性创建一个对象,使得在使用 ctypes 模块调用共享库时更容易地使用数组。返回的对象具有数据、形状和步幅属性(见下面的注释),它们本身返回可以用作共享库参数的 ctypes 对象。
参数:
无
返回:
cPython 对象
具有数据、形状、步幅等属性。
另请参阅
numpy.ctypeslib
注解
下面是该对象的公共属性,这些属性在“NumPy 指南”中有文档记录(我们已省略了未记录的公共属性和已记录的私有属性):
_ctypes.data
一个指向数组内存区域的指针,作为 Python 整数。这个内存区域可能包含未对齐或不符合正确字节顺序的数据。内存区域甚至可能不可写。将此属性传递给任意的 C 代码时应尊重这个数组的数组标志和数据类型,以避免可能导致 Python 崩溃的麻烦。用户注意!这个属性的值与 self._array_interface_['data'][0]
完全相同。
请注意,与 data_as
不同,不会保留对数组的引用:像 ctypes.c_void_p((a + b).ctypes.data)
这样的代码将导致一个指向已解除分配的数组的指针,并且应该拼写为 (a + b).ctypes.data_as(ctypes.c_void_p)
_ctypes.shape
(c_intp*self.ndim): 一个长为 self.ndim 的 ctypes 数组,其基本类型是与平台上的 dtype('p')
对应的 C 整数(请参见 c_intp
)。这个基本类型可以是 ctypes.c_int
、ctypes.c_long
或 ctypes.c_longlong
,这取决于平台。ctypes 数组包含底层数组的形状。
_ctypes.strides
(c_intp*self.ndim): 一个长为 self.ndim 的 ctypes 数组,其基本类型与形状属性相同。这个 ctypes 数组包含底层数组的步幅信息。这些步幅信息对于显示要跳过多少字节才能到达数组中的下一个元素是很重要的。
_ctypes.data_as(obj)
将数据指针强制转换为特定的 c 类型对象。例如,调用 self._as_parameter_
相当于 self.data_as(ctypes.c_void_p)
。也许您想将数据用作指向浮点数据的 ctypes 数组的指针:self.data_as(ctypes.POINTER(ctypes.c_double))
。
返回的指针将保留对数组的引用。
_ctypes.shape_as(obj)
将形状元组作为某种其他的 c 类型类型的数组返回。例如:self.shape_as(ctypes.c_short)
。
_ctypes.strides_as(obj)
以某种其他的 c 类型类型,返回作为数组的步幅元组。例如:self.strides_as(ctypes.c_longlong)
。
如果 ctypes 模块不可用,则数组对象的 ctypes 属性仍将返回有用的东西,但不会返回 ctypes 对象,而是可能会引发错误。特别是,对象仍将具有 as_parameter
属性,该属性将返回一个等于数据属性的整数。
例子
>>> import ctypes
>>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
>>> x
array([[0, 1],
[2, 3]], dtype=int32)
>>> x.ctypes.data
31962608 # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
<__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
c_uint(0)
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
c_ulong(4294967296)
>>> x.ctypes.shape
<numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
>>> x.ctypes.strides
<numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
numpy.ndarray.item
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.item.html
方法
ndarray.item(*args)
将数组的一个元素复制到标准的 Python 标量并返回它。
参数:
*args参数(数量和类型可变)
-
none:在这种情况下,该方法仅适用于只有一个元素(a.size == 1)的数组,该元素被复制到一个标准的 Python 标量对象中并返回。
-
int_type:该参数被解释为数组的扁平索引,指定要复制和返回的元素。
-
int_types 元组:功能与单个 int_type 参数相同,只是参数被解释为数组的 nd 索引。
返回:
z标准的 Python 标量对象
副本:返回一个合适的 Python 标量,它是数组的指定元素的副本。
注意事项
当a的数据类型为 longdouble 或 clongdouble 时,item()返回一个标量数组对象,因为没有可用的 Python 标量可以不丢失信息。Void 数组对 item()返回一个缓冲区对象,除非定义了字段,在这种情况下返回一个元组。
item
与 a[args]非常相似,但是返回的是一个标准的 Python 标量而不是数组标量。这对于加快访问数组元素和使用 Python 的优化数学进行数组元素的算术运算非常有用。
示例
>>> np.random.seed(123)
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[2, 2, 6],
[1, 3, 6],
[1, 0, 1]])
>>> x.item(3)
1
>>> x.item(7)
0
>>> x.item((0, 1))
2
>>> x.item((2, 2))
1
numpy.ndarray.tolist
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.tolist.html
方法
ndarray.tolist()
将数组作为深度为a.ndim
的嵌套 Python 标量列表返回。
将数组数据作为(嵌套的)Python 列表的副本返回。数据项将通过item
函数转换为最接近的兼容的内置 Python 类型。
如果a.ndim
为 0,那么由于嵌套列表的深度为 0,它根本不会是一个列表,而是一个简单的 Python 标量。
参数:
无
返回:
y对象,或对象列表,或对象列表的列表,或 …
数组元素可能嵌套的列表。
注意
可以通过a = np.array(a.tolist())
重新创建数组,尽管这有时会丢失精度。
示例
对于一维数组,a.tolist()
几乎与list(a)
相同,只不过tolist
会将 numpy 标量改变为 Python 标量:
>>> a = np.uint32([1, 2])
>>> a_list = list(a)
>>> a_list
[1, 2]
>>> type(a_list[0])
<class 'numpy.uint32'>
>>> a_tolist = a.tolist()
>>> a_tolist
[1, 2]
>>> type(a_tolist[0])
<class 'int'>
另外,对于二维数组,tolist
会递归应用:
>>> a = np.array([[1, 2], [3, 4]])
>>> list(a)
[array([1, 2]), array([3, 4])]
>>> a.tolist()
[[1, 2], [3, 4]]
这种递归的基本情形是 0 维数组:
>>> a = np.array(1)
>>> list(a)
Traceback (most recent call last):
...
TypeError: iteration over a 0-d array
>>> a.tolist()
1
numpy.ndarray.itemset
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.itemset.html
方法
ndarray.itemset(*args)
将标量插入到数组中(如果可能,将标量转换为数组的 dtype)
必须至少有 1 个参数,并将最后一个参数定义为item。然后,a.itemset(*args)
等同于但比 a[args] = item
更快。该项应为标量值,args 必须选择数组a中的单个项。
参数:
*args参数
如果一个参数:标量,仅在大小为 1 时使用。如果两个参数:最后一个参数是要设置的值,必须是标量,第一个参数指定单个数组元素的位置。它可以是 int 类型或元组。
说明
与索引语法相比,itemset
在将标量放入ndarray
的特定位置时提供了一些速度增加,如果必须这样做的话。然而,通常情况下这是不鼓励的:除了其他问题,它会使代码的外观变得复杂。此外,在循环中使用itemset
(以及item
)时,请确保将方法赋值给一个本地变量,以避免在每次循环迭代时进行属性查找。
示例
>>> np.random.seed(123)
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[2, 2, 6],
[1, 3, 6],
[1, 0, 1]])
>>> x.itemset(4, 0)
>>> x.itemset((2, 2), 9)
>>> x
array([[2, 2, 6],
[1, 0, 6],
[1, 0, 9]])
numpy.ndarray.tostring
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.tostring.html
方法
ndarray.tostring(order='C')
tobytes
的兼容别名,具有完全相同的行为。
尽管其名称如此,但返回的是字节而不是字符串。
自 1.19.0 版本起被弃用。
numpy.ndarray.tobytes
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.tobytes.html
方法
ndarray.tobytes(order='C')
构造包含数组中原始数据字节的 Python 字节。
构造出显示数据内存原始内容的 Python 字节。默认情况下,字节对象按照 C 顺序生成。这种行为由order
参数控制。
1.9.0 版本新增。
参数:
order, 可选
控制字节对象的内存布局。‘C’代表 C 顺序,‘F’代表 F 顺序,‘A’(缩写形式为 Any)表示若 a 是 Fortran 连续的则返回 ‘F’,否则返回 ‘C’。默认是 ‘C’。
返回:
sbytes
显示 a 原始数据的 Python 字节。
另见
frombuffer
通过此操作的逆操作,从 Python 字节构造一个一维数组。
示例
>>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
>>> x.tobytes()
b'\x00\x00\x01\x00\x02\x00\x03\x00'
>>> x.tobytes('C') == x.tobytes()
True
>>> x.tobytes('F')
b'\x00\x00\x02\x00\x01\x00\x03\x00'
numpy.ndarray.tofile
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.tofile.html
方法
ndarray.tofile(fid, sep='', format='%s')
将数组作为文本或二进制(默认)写入文件。
数据始终以'C'顺序写入,与a的顺序无关。此方法生成的数据可以通过 fromfile()函数恢复。
参数:
fidfile or str or Path
一个打开的文件对象或包含文件名的字符串。
从版本 1.17.0 开始更改:现在接受pathlib.Path
对象。
sepstr
文本输出中数组项之间的分隔符。如果为“”(空),则写入二进制文件,相当于file.write(a.tobytes())
。
formatstr
文本文件输出的格式字符串。数组中的每个条目都通过首先将其转换为最接近的 Python 类型,然后使用“format” % item 来格式化为文本。
注意事项
这是一个快速存储数组数据的便捷函数。丢失了字节顺序和精度的信息,因此这种方法不适用于旨在存档数据或在具有不同字节顺序的计算机之间传输数据的文件。一些问题可以通过将数据输出为文本文件来解决,但代价是速度和文件大小。
当 fid 是一个文件对象时,数组内容直接写入文件,绕过文件对象的write
方法。因此,tofile 不能与支持压缩的文件对象(例如 GzipFile)或不支持fileno()
的类文件对象(例如 BytesIO)一起使用。
numpy.ndarray.dump
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.dump.html
方法
ndarray.dump(file)
将数组的 pickle 转储到指定文件。可以使用 pickle.load 或 numpy.load 读取数组。
参数:
filestr 或 Path
一个字符串命名的转储文件。
自 1.17.0 版更改:现在接受pathlib.Path
对象。
numpy.ndarray.dumps
numpy.org/doc/1.26/reference/generated/numpy.ndarray.dumps.html
方法
ndarray.dumps()
返回数组的 pickle 形式字符串。pickle.loads 可以将字符串转换回数组。
参数:
无
numpy.ndarray.astype
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.astype.html
方法
ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
数组的副本,转换为指定的类型。
参数:
dtypestr 或 dtype
数组转换的类型代码或数据类型。
order,可选
控制结果的内存布局顺序。‘C’表示 C 顺序,‘F’表示 Fortran 顺序,‘A’表示如果所有数组都是 Fortran 连续的,则为‘F’顺序,否则为‘C’顺序,并且‘K’表示尽可能接近数组元素在内存中出现的顺序。默认为‘K’。
casting,可选
控制可能发生的数据转换类型。默认为‘unsafe’,以保持向后兼容性。
- ‘no’表示不应更改数据类型。
- ‘equiv’表示只允许字节顺序更改。
- ‘safe’表示仅允许保留值的转换。
- ‘same_kind’表示仅允许安全转换或在种类内进行转换,如 float64 到 float32。
- ‘unsafe’表示可以进行任何数据转换。
subok布尔值,可选
若为 True,则子类将被传递(默认),否则返回的数组将被强制为基类数组。
copy布尔值,可选
默认情况下,astype 始终返回一个新分配的数组。如果设置为 false,并且满足dtype
,order和subok的要求,则返回输入数组而不是副本。
返回:
arr_tndarray
除非copy
为 False 并且返回输入数组的其他条件均满足(请参见copy
输入参数的描述),arr_t是输入数组形状相同的新数组,其 dtype,order 由dtype
,order给出。
提升:
ComplexWarning
从复数到浮点数或整数的转换。要避免这种情况,应该使用a.real.astype(t)
。
注解
在版本 1.17.0 中更改:仅对于“unsafe”转换,简单数据类型和结构化类型之间的转换才可能发生。允许转换为多个字段,但不允许从多个字段转换。
从版本 1.9.0 开始更改:在“safe”转换模式下,从数值到字符串类型的转换需要字符串 dtype 的长度足够长,才能存储转换后的最大整数/浮点数值。
例子
>>> x = np.array([1, 2, 2.5])
>>> x
array([1\. , 2\. , 2.5])
>>> x.astype(int)
array([1, 2, 2])
numpy.ndarray.byteswap
numpy.org/doc/1.26/reference/generated/numpy.ndarray.byteswap.html
方法
ndarray.byteswap(inplace=False)
交换数组元素的字节
通过返回一个进行字节交换的数组,可选地就地交换,在小端和大端数据表示之间切换。字节字符串数组不进行交换。复数的实部和虚部分别进行交换。
参数:
inplace 布尔值,可选
如果True
,就地交换字节,默认为False
。
返回:
out ndarray
字节交换后的数组。如果inplace为True
,则这是对自身的视图。
示例
>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> list(map(hex, A))
['0x1', '0x100', '0x2233']
>>> A.byteswap(inplace=True)
array([ 256, 1, 13090], dtype=int16)
>>> list(map(hex, A))
['0x100', '0x1', '0x3322']
字节字符串数组不进行交换
>>> A = np.array([b'ceg', b'fac'])
>>> A.byteswap()
array([b'ceg', b'fac'], dtype='|S3')
A.newbyteorder().byteswap()
产生具有相同值的数组。
但在内存中表示方式不同
>>> A = np.array([1, 2, 3])
>>> A.view(np.uint8)
array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
0, 0], dtype=uint8)
>>> A.newbyteorder().byteswap(inplace=True)
array([1, 2, 3])
>>> A.view(np.uint8)
array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
0, 3], dtype=uint8)
numpy.ndarray.copy
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.copy.html
方法
ndarray.copy(order='C')
返回数组的副本。
参数:
order,可选
控制副本的内存布局。'C'
表示 C 顺序,'F'
表示 F 顺序,'A'
表示如果a是 Fortran 连续的,则为'F'
,否则为'C'
。'K'
表示尽可能与a的布局匹配。(注意,该函数与numpy.copy
非常相似,但对于它们的order=
参数有不同的默认值,该函数始终传递子类。)
另请参见
numpy.copy
具有不同默认行为的类似函数
numpy.copyto
注释
该函数是创建数组副本的首选方法。函数numpy.copy
相似,但默认使用'K'
顺序,并且默认情况下不传递子类。
示例
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags['C_CONTIGUOUS']
True
numpy.ndarray.view
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.view.html
方法
ndarray.view([dtype][, type])
具有相同数据的数组的新视图。
注
传递 None 给dtype
与省略参数不同,因为前者调用dtype(None)
,这是dtype('float_')
的别名。
参数:
dtype数据类型或者 ndarray 子类,可选参数
返回视图的数据类型描述符,例如,float32 或 int16。省略它会导致视图具有与a相同的数据类型。此参数也可以指定为 ndarray 子类,这样指定了返回对象的类型(这相当于设置type
参数)。
typePython 类型,可选参数
返回视图的类型,例如 ndarray 或矩阵。同样,省略该参数会保持类型不变。
注意
a.view()
有两种不同的用法:
a.view(some_dtype)
或 a.view(dtype=some_dtype)
构造具有不同数据类型的数组内存的视图。这可能会导致内存字节的重新解释。
a.view(ndarray_subclass)
或 a.view(type=ndarray_subclass)
只是返回一个查看相同数组(相同形状,dtype 等)的ndarray_subclass的实例。这不会导致对内存的重新解释。
对于a.view(some_dtype)
,如果some_dtype
每个条目的字节数与先前的数据类型不同(例如,将常规数组转换为结构化数组),那么a
的最后一个轴必须是连续的。结果中将调整该轴的大小。
1.23.0 版本中的更改:只有最后一个轴需要是连续的。以前,整个数组都必须是 C 连续的。
例子
>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
使用不同的类型和数据类型查看数组数据:
>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)
>>> print(type(y))
<class 'numpy.matrix'>
创建结构化数组上的视图,以便可以在计算中使用
>>> 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)
改变 dtype 大小(每个条目的字节数)的视图应该通常避免在由切片,转置,Fortran 顺序等定义的数组上使用:
>>> 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')])
然而,改变 dtype 的视图对于最后一个轴是连续的数组是完全可以的,即使其他轴不是 C 连续的:
>>> 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)
numpy.ndarray.getfield
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.getfield.html
方法
ndarray.getfield(dtype, offset=0)
返回给定数组的特定类型的字段。
字段是具有给定数据类型的数组数据的视图。视图中的值由给定类型和字节偏移决定到当前数组中。偏移量需要使视图的数据类型适合数组的数据类型;例如,dtype complex128 的数组具有 16 字节的元素。如果使用 32 位整数(4 字节)获取视图,则偏移量需要在 0 到 12 字节之间。
参数:
数据类型str 或 dtype
视图的数据类型。视图的数据类型大小不能大于数组本身的大小。
偏移量int
跳过开始查看元素之前的字节数。
示例
>>> x = np.diag([1.+1.j]*2)
>>> x[1, 1] = 2 + 4.j
>>> x
array([[1.+1.j, 0.+0.j],
[0.+0.j, 2.+4.j]])
>>> x.getfield(np.float64)
array([[1., 0.],
[0., 2.]])
通过选择 8 字节的偏移量,我们可以选择数组的复数部分作为我们的视图:
>>> x.getfield(np.float64, offset=8)
array([[1., 0.],
[0., 4.]])
numpy.ndarray.setflags
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.setflags.html
方法
ndarray.setflags(write=None, align=None, uic=None)
分别设置数组标志 WRITEABLE、ALIGNED、WRITEBACKIFCOPY。
这些布尔标记会影响 NumPy 解释a占用的内存区域的方式(见下面的说明)。只有在数据实际按照类型对齐时,ALIGNED 标记才能设置为 True。WRITEBACKIFCOPY 标记永远不能被设置为 True。只有当数组拥有自己的内存,或者内存的最终所有者提供了可写的缓冲区接口,或者是字符串时,WRITEABLE 标记才能设置为 True。(对于字符串的例外是为了能够在不复制内存的情况下进行反序列化。)
参数:
writebool,可选项
指示是否能够写入a。
alignbool,可选项
描述a是否对其类型进行了正确对齐。
uicbool,可选项
描述a是否是另一个“基础”数组的副本。
说明
数组标记提供有关用于数组的内存区域如何解释的信息。有 7 个正在使用的布尔标记,其中用户只能更改四个:WRITEBACKIFCOPY、WRITEABLE 和 ALIGNED。
WRITEABLE(W)可以对数据区域进行写入;
ALIGNED(A)数据和步幅在硬件上适当对齐(由编译器决定);
WRITEBACKIFCOPY(X)此数组是另一个“基础”数组的副本(由.base 引用)。在调用 C-API 函数 PyArray_ResolveWritebackIfCopy 时,基础数组将使用此数组的内容进行更新。
所有标记都可以使用单个(大写)字母以及完整名称来访问。
示例
>>> y = np.array([[3, 1, 7],
... [2, 0, 0],
... [8, 5, 9]])
>>> y
array([[3, 1, 7],
[2, 0, 0],
[8, 5, 9]])
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : False
WRITEBACKIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set WRITEBACKIFCOPY flag to True
numpy.ndarray.fill
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.fill.html
方法
ndarray.fill(value)
用标量值填充数组。
参数:
value标量
a的所有元素将被赋予这个值。
示例
>>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = np.empty(2)
>>> a.fill(1)
>>> a
array([1., 1.])
Fill 期望一个标量值,并且始终与将值赋给单个数组元素的行为相同。以下是这种区别很重要的一个罕见例子:
>>> a = np.array([None, None], dtype=object)
>>> a[0] = np.array(3)
>>> a
array([array(3), None], dtype=object)
>>> a.fill(np.array(3))
>>> a
array([array(3), array(3)], dtype=object)
在其他形式的赋值会拆开被赋值的数组时:
>>> a[...] = np.array(3)
>>> a
array([3, 3], dtype=object)
numpy.ndarray.reshape
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.reshape.html
方法
ndarray.reshape(shape, order='C')
返回一个包含相同数据的具有新形状的数组。
参考numpy.reshape
获取完整文档。
另请参阅
numpy.reshape
等效函数
注意事项
与自由函数numpy.reshape
不同,此方法允许将形状参数的元素作为单独的参数传递。例如,a.reshape(10, 11)
等效于a.reshape((10, 11))
。
numpy.ndarray.resize
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.resize.html
方法
ndarray.resize(new_shape, refcheck=True)
原地修改数组的形状和大小。
参数:
new_shapeint 元组,或n个 int
调整大小后的数组形状。
refcheckbool, 可选
如果为 False,则不会检查引用计数。默认为 True。
返回:
None
引发异常:
ValueError
如果a没有自己拥有自己的数据,或者存在对它的引用或视图,并且数据内存必须更改。只适用于 PyPy:无法可靠地确定是否存在对其的引用或视图,因此如果数据内存必须更改,则始终会引发异常。
SystemError
如果指定了order关键字参数。这种行为是 NumPy 中的一个错误。
另请参见
resize
返回一个具有指定形状的新数组。
注意
如果需要,将重新分配数据区域的空间。
只能调整连续数组(内存中连续的数据元素)的大小。
引用计数检查的目的是确保您不将此数组用作另一个 Python 对象的缓冲区,然后重新分配内存。但是,引用计数也可能以其他方式增加,因此如果您确定您没有与另一个 Python 对象共享此数组的内存,则可以将refcheck安全地设置为 False。
示例
缩小数组:数组被展平(按照内存中存储的数据顺序),调整大小并重塑:
>>> a = np.array([[0, 1], [2, 3]], order='C')
>>> a.resize((2, 1))
>>> a
array([[0],
[1]])
>>> a = np.array([[0, 1], [2, 3]], order='F')
>>> a.resize((2, 1))
>>> a
array([[0],
[2]])
扩大数组:如上所述,但缺失的条目将用零填充:
>>> b = np.array([[0, 1], [2, 3]])
>>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
>>> b
array([[0, 1, 2],
[3, 0, 0]])
引用数组会阻止调整大小…
>>> c = a
>>> a.resize((1, 1))
Traceback (most recent call last):
...
ValueError: cannot resize an array that references or is referenced ...
除非refcheck为 False:
>>> a.resize((1, 1), refcheck=False)
>>> a
array([[0]])
>>> c
array([[0]])
numpy.ndarray.transpose
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.transpose.html
method
ndarray.transpose(*axes)
返回具有轴转置的数组视图。
有关完整文档,请参阅numpy.transpose
。
参数:
axesNone, tuple of ints, or n ints
-
没有参数或空参数:颠倒轴的顺序。
-
一组整数:元组中的i位于j处,意味着数组的i轴成为转置数组的j轴。
-
n个整数:与相同整数的 n-元组相同(这种形式只是作为元组形式的“便利”替代)。
Returns:
pndarray
视图将其轴适当地重新排列。
另请参见
transpose
等效函数。
ndarray.T
返回数组的转置。
ndarray.reshape
为数组重新定义形状,而不改变数据。
示例
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
[3, 4]])
>>> a.transpose()
array([[1, 3],
[2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
[2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
[2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.transpose()
array([1, 2, 3, 4])
numpy.ndarray.swapaxes
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.swapaxes.html
方法
ndarray.swapaxes(axis1, axis2)
返回一个交换了axis1和axis2的数组视图。
参考numpy.swapaxes
了解完整文档。
另请参阅
numpy.swapaxes
等价函数
numpy.ndarray.flatten
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.flatten.html
方法
ndarray.flatten(order='C')
将数组折叠为一维的副本。
参数:
order, 可选
‘C’ 表示按行主序(C 风格)展平。‘F’ 表示按列主序(Fortran 风格)展平。‘A’ 表示如果 a 在内存中是 Fortran 连续的,则按列主序展平,否则按行主序。‘K’ 表示按内存中元素出现的顺序展平。默认为‘C’。
返回:
yndarray
输入数组的一维展平副本。
另请参阅
返回一个展平的数组。
数组的一维迭代器。
示例
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])
numpy.ndarray.ravel
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.ravel.html
方法
ndarray.ravel([order])
返回一个被展平的数组。
参考numpy.ravel
了解完整文档。
另请参阅
numpy.ravel
等效函数
ndarray.flat
该数组的扁平迭代器。
numpy.ndarray.squeeze
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.squeeze.html
方法
ndarray.squeeze(axis=None)
从a中移除长度为一的轴。
请参考numpy.squeeze
获取完整文档。
另请参阅
numpy.squeeze
等价函数
numpy.ndarray.take
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.take.html
方法
ndarray.take(indices, axis=None, out=None, mode='raise')
返回由a中给定索引处的元素形成的数组。
请参考numpy.take
查看完整文档。
另请参阅
numpy.take
等效函数
numpy.ndarray.put
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.put.html
方法
ndarray.put(indices, values, mode='raise')
将a.flat[n] = values[n]
设置为所有n中的值。
详细文档请参阅numpy.put
。
另请参阅
numpy.put
等效函数
numpy.ndarray.repeat
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.repeat.html
方法
ndarray.repeat(repeats, axis=None)
重复数组的元素。
参考numpy.repeat
获取完整文档。
另请参阅
numpy.repeat
等效函数
numpy.ndarray.choose
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.choose.html
方法
ndarray.choose(choices, out=None, mode='raise')
使用索引数组从一组选择中构建新的数组。
有关详细文档,请参阅numpy.choose
。
另请参阅
numpy.choose
等效函数
numpy.ndarray.sort
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.sort.html
方法
ndarray.sort(axis=-1, kind=None, order=None)
对数组进行就地排序。详细文档请参见 numpy.sort
。
参数:
axisint,可选
要排序的轴。默认值为-1,表示沿最后一个轴进行排序。
kind,可选
排序算法。默认值为“quicksort”。注意,‘stable’和‘mergesort’都在内部使用 timsort,并且实际实现通常会随数据类型的不同而变化。为了向后兼容,保留了‘mergesort’选项。
版本 1.15.0 中的更改:添加了“stable”选项。
orderstr 或 str 列表,可选
当 a 是一个具有已定义字段的数组时,此参数指定要首先比较的字段、第二个字段等。可以指定单个字段作为字符串,不需要指定所有字段,但未指定的字段仍将按照它们在 dtype 中出现的顺序使用,以打破平局。
另请参见
numpy.sort
返回一个已排序的数组副本。
numpy.argsort
间接排序。
numpy.lexsort
多个键的间接稳定排序。
numpy.searchsorted
在已排序的数组中查找元素。
numpy.partition
部分排序。
注意事项
查看 numpy.sort
了解不同排序算法的说明。
示例
>>> a = np.array([[1,4], [3,1]])
>>> a.sort(axis=1)
>>> a
array([[1, 4],
[1, 3]])
>>> a.sort(axis=0)
>>> a
array([[1, 3],
[1, 4]])
使用 order 关键字指定在排序结构化数组时要使用的字段:
>>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
>>> a.sort(order='y')
>>> a
array([(b'c', 1), (b'a', 2)],
dtype=[('x', 'S1'), ('y', '<i8')])
numpy.ndarray.argsort
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.argsort.html
方法
ndarray.argsort(axis=-1, kind=None, order=None)
返回对数组进行排序的索引。
参考numpy.argsort
以获取完整的文档。
另请参阅
numpy.argsort
等效函数
numpy.ndarray.partition
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.partition.html
方法
ndarray.partition(kth, axis=-1, kind='introselect', order=None)
对数组中的元素进行重新排列,使得第 k 个位置上的元素的值处于排序后数组中的位置。所有小于第 k 个元素的元素都被移动到该元素之前,所有相等或更大的元素都被移动到该元素之后。两个分区中的元素排序是未定义的。
从版本 1.8.0 开始提供。
参数:
第 k 个int 或 int 序列
按元素索引分区。第 k 个元素的值将处于其最终排序位置,并且所有较小的元素将在其之前移动,所有相等或更大的元素将在其之后移动。分区中所有元素的顺序是未定义的。如果提供了一个 kth 序列,它将会一次将由它们的第 k 个索引的所有元素分区到其排序位置。
从版本 1.22.0 开始弃用:作为索引传递布尔值已被弃用。
轴int,可选
排序的轴。默认为-1,表示沿着最后一个轴排序。
种类,可选
选择算法。默认值为‘introselect’。
顺序str 或 str 列表,可选
当a是一个定义了字段的数组时,该参数指定要首先比较哪些字段,第二个字段等。可以将单个字段指定为字符串,并不必指定所有字段,但未指定的字段仍将被使用,在 dtype 中出现的顺序会被用来打破关系。
另请参阅
numpy.partition
返回数组的分区副本。
argpartition
间接分区。
排序
完全排序。
笔记
请参阅np.partition
以了解有关不同算法的注释。
示例
>>> a = np.array([3, 4, 2, 1])
>>> a.partition(3)
>>> a
array([2, 1, 3, 4])
>>> a.partition((1, 3))
>>> a
array([1, 2, 3, 4])
numpy.ndarray.argpartition
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.argpartition.html
方法
ndarray.argpartition(kth, axis=-1, kind='introselect', order=None)
返回对数组进行分区的索引。
请参阅numpy.argpartition
了解完整文档。
在 1.8.0 版中新增。
另请参阅
numpy.argpartition
等效函数
numpy.ndarray.searchsorted
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.searchsorted.html
方法
ndarray.searchsorted(v, side='left', sorter=None)
查找应将 v 的元素插入 a 以保持顺序的索引。
查看完整文档,请参阅numpy.searchsorted
另请参阅
numpy.searchsorted
等效函数
numpy.ndarray.nonzero
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.nonzero.html
方法
ndarray.nonzero()
返回非零元素的索引。
请参考numpy.nonzero
获取完整文档。
另请参阅
numpy.nonzero
等效函数
numpy.ndarray.compress
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.compress.html
方法
ndarray.compress(condition, axis=None, out=None)
返回沿指定轴选择的数组切片。
参考numpy.compress
获取完整文档。
另请参阅
numpy.compress
等效函数
numpy.ndarray.diagonal
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.diagonal.html
方法
ndarray.diagonal(offset=0, axis1=0, axis2=1)
返回指定的对角线。在 NumPy 1.9 中,返回的数组是一个只读视图,而不是像以前的 NumPy 版本中那样是一个副本。在将来的版本中,只读限制将被移除。
请参考numpy.diagonal
获取完整文档。
另请参阅
numpy.diagonal
等效函数
numpy.ndarray.max
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.max.html
方法
ndarray.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
返回沿指定轴的最大值。
参考numpy.amax
获取完整文档。
另请参阅
numpy.amax
等效函数
numpy.ndarray.argmax
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.argmax.html
方法
ndarray.argmax(axis=None, out=None, *, keepdims=False)
返回沿给定轴的最大值的索引。
有关完整文档,请参考numpy.argmax
。
另请参阅
numpy.argmax
等效函数
numpy.ndarray.min
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.min.html
方法
ndarray.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
返回沿指定轴的最小值。
请参考numpy.amin
获取完整文档。
另请参阅
numpy.amin
等效函数
numpy.ndarray.argmin
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.argmin.html
方法
ndarray.argmin(axis=None, out=None, *, keepdims=False)
返回沿给定轴的最小值的索引。
有关详细文档,请参考numpy.argmin
。
另请参阅
numpy.argmin
等效函数
numpy.ndarray.ptp
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.ptp.html
方法
ndarray.ptp(axis=None, out=None, keepdims=False)
峰值到峰值(最大值 - 最小值)沿着给定轴的数值。
参考numpy.ptp
获取完整文档。
另请参阅
numpy.ptp
等效函数
numpy.ndarray.clip
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.clip.html
方法
ndarray.clip(min=None, max=None, out=None, **kwargs)
返回一个数值被限制在[min, max]
范围内的数组。max 和 min 中必须给定一个。
详细文档请参考numpy.clip
。
另请参阅
numpy.clip
等效函数
numpy.ndarray.conj
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.conj.html
方法
ndarray.conj()
对所有元素进行复共轭。
请参考 numpy.conjugate 获取完整文档。
参见
numpy.conjugate 参考
等效函数
numpy.ndarray.round
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.round.html
方法
ndarray.round(decimals=0, out=None)
返回* a *,其中每个元素四舍五入到给定的小数位数。
参考numpy.around
获取完整文档。
另请参阅
numpy.around
等效函数
numpy.ndarray.trace
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.trace.html
方法
ndarray.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
返回数组沿对角线的和。
参考numpy.trace
获取完整文档。
另请参阅
numpy.trace
等效函数
numpy.ndarray.sum
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.sum.html
方法
ndarray.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
返回沿给定轴的数组元素的总和。
请参考numpy.sum
获取完整文档。
另请参阅
numpy.sum
等效函数
numpy.ndarray.cumsum
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.cumsum.html
方法
ndarray.cumsum(axis=None, dtype=None, out=None)
返回沿给定轴的元素的累积和。
有关完整文档,请参考numpy.cumsum
。
另请参阅
numpy.cumsum
等效函数
numpy.ndarray.mean
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.mean.html
方法
ndarray.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
返回沿给定轴的数组元素的平均值。
请参考numpy.mean
获取完整文档。
另请参阅
numpy.mean
等效函数
numpy.ndarray.var
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.var.html
方法
ndarray.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
返回沿指定轴的数组元素的方差。
参考numpy.var
获取完整文档。
另请参阅
numpy.var
等效函数
numpy.ndarray.std
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.std.html
方法
ndarray.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
返回沿给定轴的数组元素的标准差。
参考numpy.std
获取完整文档。
另请参阅
numpy.std
等效函数
numpy.ndarray.prod
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.prod.html
方法
ndarray.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)
返回沿给定轴的数组元素的乘积
请参考numpy.prod
获取完整文档。
另请参阅
numpy.prod
等效函数
numpy.ndarray.cumprod
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.cumprod.html
方法
ndarray.cumprod(axis=None, dtype=None, out=None)
返回沿着给定轴的元素的累积乘积。
请参考numpy.cumprod
获取完整文档。
参见
numpy.cumprod
等效函数
numpy.ndarray.all
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.all.html
方法
ndarray.all(axis=None, out=None, keepdims=False, *, where=True)
如果所有元素都评估为 True,则返回 True。
请参考numpy.all
获取完整文档。
参见
numpy.all
等效函数
numpy.ndarray.any
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.any.html
方法
ndarray.any(axis=None, out=None, keepdims=False, *, where=True)
如果a的任何元素求值为 True,则返回 True。
参考numpy.any
获取完整文档。
另请参阅
numpy.any
等效函数
numpy.ndarray.__lt__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__lt__.html
方法
ndarray.__lt__(value, /)
返回 self<value。
numpy.ndarray.__le__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__le__.html
方法
ndarray.__le__(value, /)
返回 self<=value。
numpy.ndarray.__gt__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__gt__.html
方法
ndarray.__gt__(value, /)
返回 self>value。
numpy.ndarray.__ge__
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__ge__.html
方法
ndarray.__ge__(value, /)
返回 self>=value。
numpy.ndarray.__eq__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__eq__.html
方法
ndarray.__eq__(value, /)
返回 self==value.
numpy.ndarray.__ne__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__ne__.html
方法
ndarray.__ne__(value, /)
返回 self!=value。
numpy.ndarray.__bool__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__bool__.html
方法
ndarray.__bool__(/)
如果 self 为真则为 True,否则为 False
numpy.ndarray.__neg__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__neg__.html
方法
ndarray.__neg__(/)
-self
numpy.ndarray.__pos__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__pos__.html
方法
ndarray.__pos__(/)
+self
numpy.ndarray.__abs__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__abs__.html
方法
ndarray.__abs__(self)
numpy.ndarray.__invert__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__invert__.html
方法
ndarray.__invert__(/)
~self
numpy.ndarray.__add__
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__add__.html
方法
ndarray.__add__(value, /)
返回 self+value。
numpy.ndarray.__sub__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__sub__.html
方法
ndarray.__sub__(value, /)
返回自身数值。
numpy.ndarray.__mul__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__mul__.html
方法
ndarray.__mul__(value, /)
返回 self*value。
numpy.ndarray.__truediv__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__truediv__.html
方法
ndarray.__truediv__(value, /)
返回自身/值。
numpy.ndarray.__floordiv__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__floordiv__.html
方法
ndarray.__floordiv__(value, /)
返回 self//value。
numpy.ndarray.__mod__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__mod__.html
方法
ndarray.__mod__(value, /)
返回 self%value。
numpy.ndarray.__divmod__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__divmod__.html
方法
ndarray.__divmod__(value, /)
返回 divmod(self, value)。
numpy.ndarray.__pow__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__pow__.html
方法
ndarray.__pow__(value, mod=None, /)
返回 pow(self, value, mod)。
numpy.ndarray.__lshift__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__lshift__.html
方法
ndarray.__lshift__(value, /)
返回 self<<value.
numpy.ndarray.__rshift__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__rshift__.html
方法
ndarray.__rshift__(value, /)
返回 self>>value.
numpy.ndarray.__and__
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__and__.html
方法
ndarray.__and__(value, /)
返回 self&value。
numpy.ndarray.__or__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__or__.html
方法
ndarray.__or__(value, /)
返回自身|值。
numpy.ndarray.__xor__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__xor__.html
方法
ndarray.__xor__(value, /)
返回 self^value。
numpy.ndarray.__iadd__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__iadd__.html
方法
ndarray.__iadd__(value, /)
返回 self+=value。
numpy.ndarray.__isub__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__isub__.html
方法
ndarray.__isub__(value, /)
返回 self-=value。
numpy.ndarray.__imul__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__imul__.html
方法
ndarray.__imul__(value, /)
返回 self*=value.
numpy.ndarray.__itruediv__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__itruediv__.html
方法
ndarray.__itruediv__(value, /)
返回 self/=value.
numpy.ndarray.__ifloordiv__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__ifloordiv__.html
方法
ndarray.__ifloordiv__(value, /)
返回 self//=value。
numpy.ndarray.__imod__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__imod__.html
方法
ndarray.__imod__(value, /)
返回 self%=value。
numpy.ndarray.__ipow__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__ipow__.html
方法
ndarray.__ipow__(value, /)
返回 self**=value.
numpy.ndarray.__ilshift__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__ilshift__.html
方法
ndarray.__ilshift__(value, /)
返回 self<<=value。
numpy.ndarray.__irshift__
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__irshift__.html
方法
ndarray.__irshift__(value, /)
返回 self>>=value。
numpy.ndarray.__iand__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__iand__.html
方法
ndarray.__iand__(value, /)
返回 self&=value。
numpy.ndarray.__ior__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__ior__.html
方法
ndarray.__ior__(value, /)
返回 self|=value。
numpy.ndarray.__ixor__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__ixor__.html
方法
ndarray.__ixor__(value, /)
返回 self^=value.
numpy.ndarray.__matmul__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__matmul__.html
方法
ndarray.__matmul__(value, /)
返回 self@value。
numpy.ndarray.__copy__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__copy__.html
方法
ndarray.__copy__()
如果在数组上调用copy.copy
,则使用。返回数组的副本。
等同于 a.copy(order='K')
。
numpy.ndarray.__deepcopy__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__deepcopy__.html
方法
ndarray.__deepcopy__(memo, /)
当在数组上调用copy.deepcopy
时使用。
numpy.ndarray.__reduce__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__reduce__.html
方法
ndarray.__reduce__()
用于腌制。
numpy.ndarray.__setstate__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__setstate__.html
方法
ndarray.__setstate__(state, /)
用于反序列化。
state参数必须是包含以下元素的序列:
参数:
version整数
可选的 pickle 版本。如果省略,默认为 0。
shape元组
dtype数据类型
isFortran布尔值
rawdata字符串或列表
一个包含数据的二进制字符串(如果‘a’是对象数组,则为列表)
numpy.ndarray.__new__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__new__.html
方法
ndarray.__new__(*args, **kwargs)
numpy.ndarray.__array__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__array__.html
方法
ndarray.__array__([dtype, ]/)
如果未给出 dtype,则返回对 self 的新引用,如果 dtype 与数组的当前 dtype 不同,则返回提供的数据类型的新数组。
numpy.ndarray.__array_wrap__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__array_wrap__.html
方法
ndarray.__array_wrap__(array, [context, ]/)
返回一个与 self 相同类型的 array
视图。
numpy.ndarray.__len__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__len__.html
方法
ndarray.__len__(/)
返回 len(self)。
numpy.ndarray.__getitem__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__getitem__.html
方法
ndarray.__getitem__(key, /)
返回 self[key]。
numpy.ndarray.__setitem__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__setitem__.html
方法
ndarray.__setitem__(key, value, /)
将 self[key]设置为 value。
numpy.ndarray.__contains__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__contains__.html
方法
ndarray.__contains__(key, /)
返回 self 中的键。
numpy.ndarray.__int__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__int__.html
方法
ndarray.__int__(self)
numpy.ndarray.__float__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__float__.html
方法
ndarray.__float__(self)
numpy.ndarray.__complex__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__complex__.html
方法
ndarray.__complex__()
numpy.ndarray.__str__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__str__.html
方法
ndarray.__str__(/)
返回 str(self)。
numpy.ndarray.__repr__
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__repr__.html
方法
ndarray.__repr__(/)
返回 repr(self).
numpy.ndarray.__class_getitem__
原文:
numpy.org/doc/1.26/reference/generated/numpy.ndarray.__class_getitem__.html
方法
ndarray.__class_getitem__(item, /)
返回一个围绕ndarray
类型的参数化包装器。
自版本 1.22 起新增。
返回:
别名types.GenericAlias
一个参数化的ndarray
类型。
另请参阅
在标准集合中对泛型进行类型提示。
numpy.typing.NDArray
相对于其dtype.type
的一个 ndarray 别名泛型。
示例
>>> from typing import Any
>>> import numpy as np
>>> np.ndarray[Any, np.dtype[Any]]
numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
标量
Python 仅定义了特定数据类的一种类型(只有一种整数类型,一种浮点类型等)。这在不需要考虑数据在计算机中的所有表示方式的应用程序中可能很方便。然而,对于科学计算,通常需要更多的控制。
在 NumPy 中,有 24 种新的基本 Python 类型来描述不同类型的标量。这些类型描述符主要基于 CPython 编写的 C 语言中可用的类型,还有几种与 Python 类型兼容的附加类型。
数组标量具有与ndarrays
相同的属性和方法。[1] 这使得可以将数组的项部分地与数组相同地对待,从而平滑混合标量和数组操作时产生的粗糙边缘。
数组标量存在于数据类型的层次结构中(见下图)。可以使用层次结构检测它们:例如,isinstance(val, np.generic)
将返回True
,如果val是一个数组标量对象。另外,可以使用数据类型层次结构的其他成员来确定存在哪种数组标量。因此,例如,如果val是复数类型,则isinstance(val, np.complexfloating)
将返回True
,而如果val是灵活项大小数组类型之一(str_
,bytes_
,void
),则isinstance(val, np.flexible)
将返回 true。
图: 表示数组数据类型的类型对象层次结构。未显示的是指向平台上保存指针的整数类型intp
和uintp
。所有数字类型都可以使用位宽名称获取。
内置标量类型
内置标量类型如下所示。与字符代码相关联的 C 样式名称显示在其描述中。然而,不建议使用字符代码。
一些标量类型本质上等同于基本的 Python 类型,因此也继承自它们以及通用的数组标量类型:
数组标量类型 | 相关的 Python 类型 | 继承? |
---|---|---|
int_ |
int |
仅 Python 2 |
float_ |
float |
是 |
complex_ |
complex |
是 |
bytes_ |
bytes |
是 |
str_ |
str |
是 |
bool_ |
bool |
否 |
datetime64 |
datetime.datetime |
否 |
timedelta64 |
datetime.timedelta |
否 |
bool_
数据类型与 Python bool
非常相似,但不继承自它,因为 Python 的 bool
不允许被继承,并且在 C 级别上,实际布尔数据的大小与 Python 布尔标量不同。
警告
int_
类型不继承自int
在 Python 3 下,因为类型int
不再是固定宽度整数类型。
提示
NumPy 中的默认数据类型是float_
。
class numpy.generic
numpy 标量类型的基类。
大多数(全部?)numpy 标量类型派生的类。为了一致性,尽管许多随后的属性要么是“只读”,要么完全无关紧要,但暴露与ndarray
相同的 API。这是强烈建议用户应该从中派生自定义标量类型的类。
class numpy.number
所有数值标量类型的抽象基类。
整数类型
class numpy.integer
所有整数标量类型的抽象基类。
注意
numpy 整数类型反映了 C 整数的行为,因此可能会受到溢出错误的影响。
有符号整数类型
class numpy.signedinteger
所有有符号整数标量类型的抽象基类。
class numpy.byte
有符号整数类型,与 C char
兼容。
字符编码:
'b'
在此平台上的别名(Linux x86_64):
numpy.int8
: 8 位有符号整数(-128
到 127
)。
class numpy.short
有符号整数类型,与 C short
兼容。
字符编码:
'h'
在此平台上的别名(Linux x86_64):
numpy.int16
: 16 位有符号整数(-32_768
到 32_767
)。
class numpy.intc
有符号整数类型,与 C int
兼容。
字符编码:
'i'
在此平台上的别名(Linux x86_64):
numpy.int32
:32 位有符号整数(-2_147_483_648
到 2_147_483_647
)。
class numpy.int_
有符号整数类型,与 Python int 和 C 中的long
兼容。
字符编码:
'l'
在此平台上的别名(Linux x86_64):
numpy.int64
:64 位有符号整数(-9_223_372_036_854_775_808
到 9_223_372_036_854_775_807
)。
在此平台上的别名(Linux x86_64):
numpy.intp
:足够大以容纳指针的有符号整数,与 C 中的intptr_t
兼容。
class numpy.longlong
有符号整数类型,与 C 中的long long
兼容。
字符编码:
'q'
无符号整数类型
class numpy.unsignedinteger
所有无符号整数标量类型的抽象基类。
class numpy.ubyte
无符号整数类型,与 C 中的unsigned char
兼容。
字符编码:
'B'
在此平台上的别名(Linux x86_64):
numpy.uint8
:8 位无符号整数(0
到 255
)。
class numpy.ushort
无符号整数类型,与 C 中的unsigned short
兼容。
字符编码:
'H'
在此平台上的别名(Linux x86_64):
numpy.uint16
:16 位无���号整数(0
到 65_535
)。
class numpy.uintc
无符号整数类型,与 C 中的unsigned int
兼容。
字符编码:
'I'
在此平台上的别名(Linux x86_64):
numpy.uint32
:32 位无符号整数(0
到 4_294_967_295
)。
class numpy.uint
无符号整数类型,与 C 中的unsigned long
兼容。
字符编码:
'L'
在此平台上的别名(Linux x86_64):
numpy.uint64
:64 位无符号整数(0
到 18_446_744_073_709_551_615
)。
在此平台上的别名(Linux x86_64):
numpy.uintp
:足够大以容纳指针的无符号整数,与 C 中的uintptr_t
兼容。
class numpy.ulonglong
有符号整数类型,与 C 中的unsigned long long
兼容。
字符编码:
'Q'
非精确类型
class numpy.inexact
所有数值标量类型的抽象基类,其值的表示(可能)不精确,例如浮点数。
注意
使用最少的十进制数字打印不精确标量,以区分其值与同一数据类型的其他值,通过谨慎的四舍五入。参见format_float_positional
和format_float_scientific
的unique
参数。
这意味着具有相同二进制值但数据类型精度不同的变量可能显示不同:
>>> f16 = np.float16("0.1")
>>> f32 = np.float32(f16)
>>> f64 = np.float64(f32)
>>> f16 == f32 == f64
True
>>> f16, f32, f64
(0.1, 0.099975586, 0.0999755859375)
注意,这些浮点数中没有一个能够精确表示 (\frac{1}{10}) 的值;f16
打印为0.1
,因为它尽可能接近该值,而其他类型则不会,因为它们具有更高的精度,因此具有更接近的值。
相反,不同精度的浮点标量可能近似相同的十进制值,但尽管打印相同,它们可能不相等:
>>> f16 = np.float16("0.1")
>>> f32 = np.float32("0.1")
>>> f64 = np.float64("0.1")
>>> f16 == f32 == f64
False
>>> f16, f32, f64
(0.1, 0.1, 0.1)
浮点数类型
class numpy.floating
所有浮点数标量类型的抽象基类。
class numpy.half
半精度浮点数类型。
字符编码:
'e'
在此平台(Linux x86_64)上的别名:
numpy.float16
: 16 位精度浮点数类型:符号位,5 位指数,10 位尾数。
class numpy.single
单精度浮点数类型,与 C 中的float
兼容。
字符编码:
'f'
在此平台(Linux x86_64)上的别名:
numpy.float32
: 32 位精度浮点数类型:符号位,8 位指数,23 位尾数。
class numpy.double(x=0, /)
双精度浮点数类型,与 Python 的float和 C 中的double
兼容。
字符编码:
'd'
别名:
numpy.float_
在此平台(Linux x86_64)上的别名:
numpy.float64
: 64 位精度浮点数类型:符号位,11 位指数,52 位尾数。
class numpy.longdouble
扩展精度浮点数类型,与 C 中的long double
兼容,但不一定与 IEEE 754 四倍精度兼容。
字符编码:
'g'
别名:
numpy.longfloat
在此平台(Linux x86_64)上的别名:
numpy.float128
: 128 位扩展精度浮点数类型。
复数浮点类型
class numpy.complexfloating
所有由浮点数组成的复数标量类型的抽象基类。
class numpy.csingle
由两个单精度浮点数组成的复数类型。
字符编码:
'F'
别名:
numpy.singlecomplex
在此平台(Linux x86_64)上的别名:
numpy.complex64
: 由两个 32 位精度浮点数组成的复数类型。
class numpy.cdouble(real=0, imag=0)
由两个双精度浮点数组成的复数类型,与 Python 的complex兼容。
字符编码:
'D'
别名:
numpy.cfloat
别名:
numpy.complex_
在此平台(Linux x86_64)上的别名:
numpy.complex128
: 由两个 64 位精度浮点数组成的复数类型。
class numpy.clongdouble
由两个扩展精度浮点数组成的复数类型。
字符编码:
'G'
别名:
numpy.clongfloat
别名:
numpy.longcomplex
在此平台(Linux x86_64)上的别名:
numpy.complex256
: 由两个 128 位扩展精度浮点数组成的复数类型。
其他类型
class numpy.bool_
布尔类型(True 或 False),以字节形式存储。
警告
bool_
类型不是int_
类型的子类(bool_
甚至不是一个数字类型)。这与 Python 默认实现中将bool
作为int
的子类的方式不同。
字符编码:
'?'
class numpy.datetime64
如果从 64 位整数创建,它表示从1970-01-01T00:00:00
的偏移量。如果从字符串创建,字符串可以是 ISO 8601 日期或日期时间格式。
>>> np.datetime64(10, 'Y')
numpy.datetime64('1980')
>>> np.datetime64('1980', 'Y')
numpy.datetime64('1980')
>>> np.datetime64(10, 'D')
numpy.datetime64('1970-01-11')
更多信息请参见日期时间和时间增量。
字符编码:
'M'
class numpy.timedelta64
以 64 位整数存储的时间增量。
更多信息请参见日期时间和时间增量。
字符编码:
'm'
class numpy.object_
任何 Python 对象。
字符编码:
'O'
注意
实际存储在对象数组中(即,具有 dtype object_
的数组)的数据是对 Python 对象的引用,而不是对象本身。因此,对象数组的行为更像是通常的 Python lists
,即它们的内容不必是相同的 Python 类型。
对象类型也很特殊,因为包含object_
项的数组在访问项时不会返回object_
对象,而是返回数组项实际引用的对象。
以下数据类型是灵活的:它们没有预定义的大小,它们描述的数据在不同数组中的长度可以不同。(在字符代码中,#
是一个整数,表示数据类型包含多少个元素。)
class numpy.flexible
所有没有预定义长度的标量类型的抽象基类。这些类型的实际大小取决于特定的np.dtype实例化。
class numpy.character
所有字符字符串标量类型的抽象基类。
class numpy.bytes_
一个字节字符串。
在数组中使用时,此类型会去除尾随的空字节。
字符编码:
'S'
别名:
numpy.string_
class numpy.str_
Unicode 字符串。
此类型会去除尾随的空代码点。
>>> s = np.str_("abc\x00")
>>> s
'abc'
与内置str不同,此类型支持缓冲区协议,将其内容公开为 UCS4:
>>> m = memoryview(np.str_("abc"))
>>> m.format
'3w'
>>> m.tobytes()
b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
字符编码:
'U'
别名:
numpy.unicode_
class numpy.void(length_or_data, /, dtype=None)
创建一个新的结构化或未结构化空白标量。
参数:
length_or_dataint,类似数组,类似字节,对象
多重含义之一(请参阅注释)。未结构化空白的长度或字节数据。或者,当提供dtype
时,要存储在新标量中的数据。这可以是类似数组的东西,如果是这种情况,可能会返回一个数组。
dtypedtype,可选
如果提供了新标量的 dtype。此 dtype 必须是“void” dtype(即结构化或非结构化 void,请参阅结构化数据类型)。
..versionadded:: 1.24
注释
出于历史原因和因为 void 标量可以表示任意字节数据和结构化数据类型,void 构造函数有三种调用约定:
-
np.void(5)
创建一个填充有五个\0
字节的dtype="V5"
标量。这里的 5 可以是 Python 或 NumPy 整数。 -
np.void(b"bytes-like")
从字节字符串创建一个 void 标量。dtype 的 itemsize 将匹配字节字符串的长度,这里是"V10"
。 -
当传递
dtype=
时,调用与数组创建大致相同。但是,返回的是一个 void 标量而不是数组。
请查看展示所有三种不同约定的示例。
示例
>>> np.void(5)
void(b'\x00\x00\x00\x00\x00')
>>> np.void(b'abcd')
void(b'\x61\x62\x63\x64')
>>> np.void((5, 3.2, "eggs"), dtype="i,d,S5")
(5, 3.2, b'eggs') # looks like a tuple, but is `np.void`
>>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
(3, 3) # looks like a tuple, but is `np.void`
字符代码:
'V'
警告
请参阅字符串类型注释。
数值兼容性:如果您在您的 Numeric 代码中使用了旧的类型代码字符(这从未被推荐过),您将需要将其中一些更改为新字符。特别是,需要更改的是 c -> S1
、b -> B
、1 -> b
、s -> h
、w -> H
和u -> I
。这些更改使类型字符约定更加一致,与其他 Python 模块(如struct
模块)一致。
大小别名
除了它们(大部分)源自 C 的名称外,整数、浮点数和复数数据类型也可以使用位宽约定来使用,以确保始终可以确保正确大小的数组。还提供了两个别名(numpy.intp
和numpy.uintp
),指向足够大以容纳 C 指针的整数类型。
numpy.int8
numpy.int16
numpy.int32
numpy.int64
有指定位数的有符号整数类型的别名(numpy.byte
、numpy.short
、numpy.intc
、numpy.int_
和numpy.longlong
之一)。
兼容于 C99 int8_t
、int16_t
、int32_t
和int64_t
。
numpy.uint8
numpy.uint16
numpy.uint32
numpy.uint64
无符号整数类型的别名(numpy.ubyte
、numpy.ushort
、numpy.uintc
、numpy.uint
和numpy.ulonglong
之一)。
兼容于 C99 uint8_t
、uint16_t
、uint32_t
和uint64_t
。
numpy.intp
有相同大小作为指针的有符号整数类型的别名(numpy.byte
、numpy.short
、numpy.intc
、numpy.int_
和np.longlong)。
兼容于 C intptr_t
。
字符代码:
'p'
numpy.uintp
无符号整数类型的别名(其中之一是numpy.ubyte
,numpy.ushort
,numpy.uintc
,numpy.uint
和np.ulonglong),与指针大小相同。
与 C uintptr_t
兼容。
字符代码:
'P'
numpy.float16
half
的别名
numpy.float32
single
的别名
numpy.float64
double
的别名
numpy.float96
numpy.float128
别名为numpy.longdouble
,根据其位数命名。这些别名的存在取决于平台。
numpy.complex64
csingle
的别名
numpy.complex128
cdouble
的别名
numpy.complex192
numpy.complex256
别名为numpy.clongdouble
,根据其位数命名。这些别名的存在取决于平台。
其他别名
前两个是类似于内置类型名称的便利方式,与bool_
,int_
,str_
,bytes_
和object_
相同风格:
numpy.float_
double
的别名
numpy.complex_
cdouble
的别名
一些使用扩展精度浮点数和复数的备用命名约定:
numpy.longfloat
longdouble
的别名
numpy.singlecomplex
csingle
的别名
numpy.cfloat
cdouble
的别名
numpy.longcomplex
clongdouble
的别名
numpy.clongfloat
clongdouble
的别名
以下别名源自 Python 2,建议不要在新代码中使用它们。
numpy.string_
bytes_
的别名
numpy.unicode_
str_
的别名
属性
数组标量对象具有NPY_SCALAR_PRIORITY
(-1,000,000.0)的array priority
。它们还没有(但是)具有ctypes
属性。否则,它们与数组共享相同的属性:
generic.flags |
标志的整数值。 |
---|---|
generic.shape |
数组维度的元组。 |
generic.strides |
每个维度中的字节步长元组。 |
generic.ndim |
数组维度的数量。 |
generic.data |
数据起始指针。 |
generic.size |
gentype 中元素的数量。 |
generic.itemsize |
一个元素的长度(以字节为单位)。 |
generic.base |
与相应数组属性相同的标量属性。 |
generic.dtype |
获取数组数据描述符。 |
generic.real |
标量的实部。 |
generic.imag |
标量的虚部。 |
generic.flat |
标量的 1-D 视图。 |
generic.T |
与相应数组属性相同的标量属性。 |
generic.__array_interface__ |
数组协议:Python 端 |
generic.__array_struct__ |
数组协议:结构 |
generic.__array_priority__ |
数组优先级。 |
generic.__array_wrap__ |
sc.array_wrap(obj) 从数组返回标量 |
索引
另请参阅
索引例程, 数据类型对象(dtype)
数组标量可以像零维数组一样进行索引:如果 x 是一个数组标量,
-
x[()]
返回数组标量的副本 -
x[...]
返回一个零维ndarray
-
x['field-name']
返回字段 field-name 中的数组标量。 (x 可以有字段,例如,当它对应于结构化数据类型时。)
方法
数组标量具有与数组完全相同的方法。 这些方法的默认行为是将标量内部转换为等效的零维数组,并调用相应的数组方法。 此外,对数组标量的数学运算被定义为设置相同的硬件标志并用于解释结果,就像对 ufunc 一样,因此对数组标量的数学运算也继承了用于 ufuncs 的错误状态。
以上规则的例外情况如下:
generic.__array__ |
sc.array(dtype) 从具有指定 dtype 的标量返回 0 维数组 |
---|---|
generic.__array_wrap__ |
sc.array_wrap(obj) 从数组返回标量 |
generic.squeeze |
与相应数组属性相同的标量方法。 |
generic.byteswap |
与相应数组属性相同的标量方法。 |
generic.__reduce__ |
pickle 的辅助方法。 |
generic.__setstate__ |
|
generic.setflags |
与相应数组属性相同的标量方法。 |
类型定义实用方法:
number.__class_getitem__ (item, /) |
返回围绕number 类型的参数化包装器。 |
---|
定义新类型
有效定义新数组标量类型的两种方法(除了从内置标量类型组合结构化类型 dtypes):一种方法是简单地子类化ndarray
并重写感兴趣的方法。这在一定程度上可以工作,但在内部,某些行为是由数组的数据类型固定的。要完全自定义数组的数据类型,您需要定义一个新的数据类型,并在 NumPy 中注册它。这样的新类型只能在 C 中定义,使用 NumPy C-API。
内置标量类型
下面显示了内置标量类型。类似 C 的名称与字符代码相关联,这些字符代码显示在其描述中。然而,不建议使用字符代码。
一些标量类型本质上等同于基本的 Python 类型,因此也从它们那里继承,以及从通用数组标量类型继承:
数组标量类型 | 相关的 Python 类型 | 继承? |
---|---|---|
int_ |
int |
仅适用于 Python 2 |
float_ |
float |
是 |
complex_ |
complex |
是 |
bytes_ |
bytes |
是 |
str_ |
str |
是 |
bool_ |
bool |
否 |
datetime64 |
datetime.datetime |
否 |
timedelta64 |
datetime.timedelta |
否 |
bool_
数据类型与 Python bool
非常相似,但不继承自它,因为 Python 的bool
不允许被继承,而且在 C 级别上,实际布尔数据的大小与 Python 布尔标量不同。
警告
int_
类型不继承自 Python 3 下的int
内置类型,因为类型int
不再是固定宽度整数类型。
提示
NumPy 中的默认数据类型是float_
。
class numpy.generic
numpy 标量类型的基类。
大多数(全部?)numpy 标量类型派生自的类。为了保持一致性,尽管许多后续属性要么是“只读”,要么完全无关紧要,但它暴露与ndarray
相同的 API。强烈建议用户从这个类派生自定义标量类型。
class numpy.number
所有数值标量类型的抽象基类。
整数类型
class numpy.integer
所有整数标量类型的抽象基类。
注意
numpy 整数类型反映了 C 整数的行为,因此可能会受到溢出错误的影响。
有符号整数类型
class numpy.signedinteger
所有有符号整数标量类型的抽象基类。
class numpy.byte
有符号整数类型,与 C char
兼容。
字符编码:
'b'
在此平台上的别名(Linux x86_64):
numpy.int8
:8 位有符号整数(-128
到127
)。
class numpy.short
有符号整数类型,与 C short
兼容。
字符编码:
'h'
在此平台上的别名(Linux x86_64):
numpy.int16
:16 位有符号整数(-32_768
到32_767
)。
class numpy.intc
有符号整数类型,与 C int
兼容。
字符编码:
'i'
在此平台上的别名(Linux x86_64):
numpy.int32
:32 位有符号整数(-2_147_483_648
到2_147_483_647
)。
class numpy.int_
有符号整数类型,与 Python int和 C long
兼容。
字符编码:
'l'
该平台上的别名(Linux x86_64):
numpy.int64
: 64 位有符号整数(-9_223_372_036_854_775_808
到 9_223_372_036_854_775_807
)。
该平台上的别名(Linux x86_64):
numpy.intp
: 足够大以适应指针的有符号整数,与 C intptr_t
兼容。
class numpy.longlong
有符号整数类型,与 C long long
兼容。
字符编码:
'q'
无符号整数类型
class numpy.unsignedinteger
所有无符号整数标量类型的抽象基类。
class numpy.ubyte
无符号整数类型,与 C unsigned char
兼容。
字符编码:
'B'
该平台上的别名(Linux x86_64):
numpy.uint8
: 8 位无符号整数(0
到 255
)。
class numpy.ushort
无符号整数类型,与 C unsigned short
兼容。
字符编码:
'H'
该平台上的别名(Linux x86_64):
numpy.uint16
: 16 位无符号整数(0
到 65_535
)。
class numpy.uintc
无符号整数类型,与 C unsigned int
兼容。
字符编码:
'I'
该平台上的别名(Linux x86_64):
numpy.uint32
: 32 位无符号整数(0
到 4_294_967_295
)。
class numpy.uint
无符号整数类型,与 C unsigned long
兼容。
字符编码:
'L'
该平台上的别名(Linux x86_64):
numpy.uint64
: 64 位无符号整数(0
到 18_446_744_073_709_551_615
)。
该平台上的别名(Linux x86_64):
numpy.uintp
: 足够大以适应指针的无符号整数,与 C uintptr_t
兼容。
class numpy.ulonglong
有符号整数类型,与 C unsigned long long
兼容。
字符编码:
'Q'
不精确类型
class numpy.inexact
所有数值标量类型的抽象基类,其值在其范围内具有(可能)不精确的表示,例如浮点数。
注意
不精确的标量使用最少的十进制数字打印,以区分其值与同一数据类型的其他值,通过谨慎的四舍五入。参见 format_float_positional
和 format_float_scientific
的 unique
参数。
这意味着具有相同二进制值但数据类型精度不同的变量可能显示不同:
>>> f16 = np.float16("0.1")
>>> f32 = np.float32(f16)
>>> f64 = np.float64(f32)
>>> f16 == f32 == f64
True
>>> f16, f32, f64
(0.1, 0.099975586, 0.0999755859375)
请注意,这些浮点数中没有一个保存精确值 (\frac{1}{10});f16
打印为 0.1
,因为它尽可能接近该值,而其他类型不会,因为它们具有更高的精度,因此具有更接近的值。
相反,不同精度的浮点标量可能显示为不同的十进制值,尽管打印相同:
>>> f16 = np.float16("0.1")
>>> f32 = np.float32("0.1")
>>> f64 = np.float64("0.1")
>>> f16 == f32 == f64
False
>>> f16, f32, f64
(0.1, 0.1, 0.1)
浮点类型
class numpy.floating
所有浮点标量类型的抽象基类。
class numpy.half
半精度浮点数类��。
字符编码:
'e'
该平台上的别名(Linux x86_64):
numpy.float16
:16 位精度浮点数类型:符号位,5 位指数,10 位尾数。
class numpy.single
单精度浮点数类型,与 C float
兼容。
字符编码:
'f'
在这个平台上的别名(Linux x86_64):
numpy.float32
:32 位精度浮点数类型:符号位,8 位指数,23 位尾数。
class numpy.double(x=0, /)
双精度浮点数类型,与 Python float 和 C double
兼容。
字符编码:
'd'
别名:
numpy.float_
在这个平台上的别名(Linux x86_64):
numpy.float64
:64 位精度浮点数类型:符号位,11 位指数,52 位尾数。
class numpy.longdouble
扩展精度浮点数类型,与 C long double
兼容,但不一定与 IEEE 754 四倍精度兼容。
字符编码:
'g'
别名:
numpy.longfloat
在这个平台上的别名(Linux x86_64):
numpy.float128
:128 位扩展精度浮点数类型。
复数浮点类型
class numpy.complexfloating
所有由浮点数组成的复数标量类型的抽象基类。
class numpy.csingle
由两个单精度浮点数组成的复数类型。
字符编码:
'F'
别名:
numpy.singlecomplex
在这个平台上的别名(Linux x86_64):
numpy.complex64
:由两个 32 位精度浮点数组成的复数类型。
class numpy.cdouble(real=0, imag=0)
由两个双精度浮点数组成的复数类型,与 Python complex 兼容。
字符编码:
'D'
别名:
numpy.cfloat
别名:
numpy.complex_
在这个平台上的别名(Linux x86_64):
numpy.complex128
:由两个 64 位精度浮点数组成的复数类型。
class numpy.clongdouble
由两个扩展精度浮点数组成的复数类型。
字符编码:
'G'
别名:
numpy.clongfloat
别名:
numpy.longcomplex
在这个平台上的别名(Linux x86_64):
numpy.complex256
:由两个 128 位扩展精度浮点数组成的复数类型。
其他类型
class numpy.bool_
布尔类型(True 或 False),存储为一个字节。
警告
bool_
类型不是 int_
类型的子类(bool_
甚至不是一个数字类型)。这与 Python 默认实现的 bool
作为 int
的子类不同。
字符编码:
'?'
class numpy.datetime64
如果从 64 位整数创建,则表示从1970-01-01T00:00:00
的偏移量。如果从字符串创建,则字符串可以是 ISO 8601 日期或日期时间格式。
>>> np.datetime64(10, 'Y')
numpy.datetime64('1980')
>>> np.datetime64('1980', 'Y')
numpy.datetime64('1980')
>>> np.datetime64(10, 'D')
numpy.datetime64('1970-01-11')
更多信息请参见日期时间和时间间隔。
字符编码:
'M'
class numpy.timedelta64
以 64 位整数存储的时间间隔。
更多信息请参见日期时间和时间间隔。
字符编码:
'm'
class numpy.object_
任何 Python 对象。
字符编码:
'O'
注意
实际存储在对象数组中的数据(即具有 dtype object_
的数组)是对 Python 对象的引用,而不是对象本身。因此,对象数组的行为更像通常的 Python lists
,即它们的内容不必是相同的 Python 类型。
对象类型也很特殊,因为包含object_
项的数组在访问项时不会返回一个object_
对象,而是返回数组项所指的实际对象。
以下数据类型是灵活的:它们没有预定义的大小,它们描述的数据在不同数组中可以是不同长度的。(在字符编码中,#
是一个整数,表示数据类型包含多少个元素。)
class numpy.flexible
所有没有预定义长度的标量类型的抽象基类。这些类型的实际大小取决于特定的np.dtype实例化。
class numpy.character
所有字符字符串标量类型的抽象基类。
class numpy.bytes_
一个字节字符串。
在数组中使用时,此类型会去除尾随的空字节。
字符编码:
'S'
别名:
numpy.string_
class numpy.str_
一个 Unicode 字符串。
此类型会去除尾随的空代码点。
>>> s = np.str_("abc\x00")
>>> s
'abc'
与内置的str不同,这支持缓冲区协议,将其内容公开为 UCS4:
>>> m = memoryview(np.str_("abc"))
>>> m.format
'3w'
>>> m.tobytes()
b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
字符编码:
'U'
别名:
numpy.unicode_
class numpy.void(length_or_data, /, dtype=None)
创建一个新的结构化或无结构化空标量。
参数:
length_or_dataint,类似数组,类似字节,对象
具有多重含义之一(请参阅注释)。无结构空白的长度或字节数据。或者,当提供dtype
时要存储在新标量中的数据。这可以是类似数组的东西,如果是这种情况,可能会返回一个数组。
dtypedtype,可选
如果提供了新标量的 dtype。此 dtype 必须是“void”dtype(即结构化或无结构化空,另请参见结构化数据类型)。
..versionadded:: 1.24
注释
由于历史原因和因为空标量可以表示任意字节数据和结构化的 dtype,空构造函数有三种调用约定:
-
np.void(5)
创建一个填充有五个\0
字节的dtype="V5"
标量。5 可以是 Python 或 NumPy 整数。 -
np.void(b"bytes-like")
从字节字符串创建一个空标量。dtype 的 itemsize 将匹配字节字符串的长度,这里是"V10"
。 -
当传递
dtype=
时,调用与数组创建大致相同。但是,返回的是一个空标量而不是数组。
请查看示例,展示了所有三种不同的约定。
示例
>>> np.void(5)
void(b'\x00\x00\x00\x00\x00')
>>> np.void(b'abcd')
void(b'\x61\x62\x63\x64')
>>> np.void((5, 3.2, "eggs"), dtype="i,d,S5")
(5, 3.2, b'eggs') # looks like a tuple, but is `np.void`
>>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
(3, 3) # looks like a tuple, but is `np.void`
字符代码:
'V'
警告
请参阅字符串类型注释。
数值兼容性:如果您在 Numeric 代码中使用了旧的类型代码字符(这从未被推荐过),您将需要将其中一些更改为新字符。特别是,需要更改的是 c -> S1
,b -> B
,1 -> b
,s -> h
,w -> H
和 u -> I
。这些更改使类型字符约定更加一致,与其他 Python 模块(如 struct
模块)一致。
大小别名
除了它们(大多数)源自 C 的名称之外,整数、浮点和复数数据类型还可以使用位宽约定来使用,以确保始终可以确保正确大小的数组。还提供了两个别名(numpy.intp
和 numpy.uintp
),指向足够大以容纳 C 指针的整数类型。
numpy.int8
numpy.int16
numpy.int32
numpy.int64
具有指定位数的有符号整数类型的别名(numpy.byte
、numpy.short
、numpy.intc
、numpy.int_
和 numpy.longlong
)。
与 C99 中的 int8_t
、int16_t
、int32_t
和 int64_t
兼容。
numpy.uint8
numpy.uint16
numpy.uint32
numpy.uint64
具有指定位数的无符号整数类型的别名(numpy.ubyte
、numpy.ushort
、numpy.uintc
、numpy.uint
和 numpy.ulonglong
)。
与 C99 中的 uint8_t
、uint16_t
、uint32_t
和 uint64_t
兼容。
numpy.intp
作为指针大小相同的有符号整数类型的别名(numpy.byte
、numpy.short
、numpy.intc
、numpy.int_
和 np.longlong)。
与 C intptr_t
兼容。
字符代码:
'p'
numpy.uintp
作为指针大小相同的无符号整数类型的别名(numpy.ubyte
、numpy.ushort
、numpy.uintc
、numpy.uint
和 np.ulonglong)。
与 C uintptr_t
兼容。
字符代码:
'P'
numpy.float16
half
的别名
numpy.float32
single
的别名
numpy.float64
double
的别名
numpy.float96
numpy.float128
别名为numpy.longdouble
,根据其位数命名。这些别名的存在取决于平台。
numpy.complex64
别名为csingle
numpy.complex128
别名为cdouble
numpy.complex192
numpy.complex256
别名为numpy.clongdouble
,根据其位数命名。这些别名的存在取决于平台。
其他别名
前两个是方便起见,类似于内置类型的名称,与bool_
、int_
、str_
、bytes_
和object_
的风格相同:
numpy.float_
别名为double
numpy.complex_
别名为cdouble
一些使用扩展精度浮点数和复数的替代命名约定:
numpy.longfloat
别名为longdouble
numpy.singlecomplex
别名为csingle
numpy.cfloat
别名为cdouble
numpy.longcomplex
别名为clongdouble
numpy.clongfloat
别名为clongdouble
以下别名源自 Python 2,建议不要在新代码中使用。
numpy.string_
别名为bytes_
numpy.unicode_
别名为str_
整数类型
class numpy.integer
所有整数标量类型的抽象基类。
注意
numpy 整数类型反映了 C 整数的行为,因此可能会受到溢出错误的影响。
有符号整数类型
class numpy.signedinteger
所有有符号整数标量类型的抽象基类。
class numpy.byte
有符号整数类型,与 C char
兼容。
字符编码:
'b'
在这个平台上的别名(Linux x86_64):
numpy.int8
:8 位有符号整数(-128
到127
)。
class numpy.short
有符号整数类型,与 C short
兼容。
字符编码:
'h'
在这个平台上的别名(Linux x86_64):
numpy.int16
:16 位有符号整数(-32_768
到32_767
)。
class numpy.intc
有符号整数类型,与 C int
兼容。
字符编码:
'i'
在这个平台上的别名(Linux x86_64):
numpy.int32
:32 位有符号整数(-2_147_483_648
到2_147_483_647
)。
class numpy.int_
有符号整数类型,与 Python int和 C long
兼容。
字符编码:
'l'
在这个平台上的别名(Linux x86_64):
numpy.int64
:64 位有符号整数(-9_223_372_036_854_775_808
到9_223_372_036_854_775_807
)。
在这个平台上的别名(Linux x86_64):
numpy.intp
:足够大以适应指针的有符号整数,与 C intptr_t
兼容。
class numpy.longlong
有符号整数类型,与 C long long
兼容。
字符编码:
'q'
无符号整数类型
class numpy.unsignedinteger
所有无符号整数标量类型的抽象基类。
class numpy.ubyte
无符号整数类型,与 C unsigned char
兼容。
字符编码:
'B'
在这个平台上的别名(Linux x86_64):
numpy.uint8
: 8 位无符号整数(0
到 255
)。
class numpy.ushort
无符号整数类型,与 C unsigned short
兼容。
字符编码:
'H'
在这个平台上的别名(Linux x86_64):
numpy.uint16
: 16 位无符号整数(0
到 65_535
)。
class numpy.uintc
无符号整数类型,与 C unsigned int
兼容。
字符编码:
'I'
在这个平台上的别名(Linux x86_64):
numpy.uint32
: 32 位无符号整数(0
到 4_294_967_295
)。
class numpy.uint
无符号整数类型,与 C unsigned long
兼容。
字符编码:
'L'
在这个平台上的别名(Linux x86_64):
numpy.uint64
: 64 位无符号整数(0
到 18_446_744_073_709_551_615
)。
在这个平台上的别名(Linux x86_64):
numpy.uintp
: 足够大以容纳指针的无符号整数,与 C uintptr_t
兼容。
class numpy.ulonglong
有符号整数类型,与 C unsigned long long
兼容。
字符编码:
'Q'
有符号整数类型
class numpy.signedinteger
所有有符号整数标量类型的抽象基类。
class numpy.byte
有符号整数类型,与 C char
兼容。
字符编码:
'b'
在这个平台上的别名(Linux x86_64):
numpy.int8
: 8 位有符号整数(-128
到 127
)。
class numpy.short
有符号整数类型,与 C short
兼容。
字符编码:
'h'
在这个平台上的别名(Linux x86_64):
numpy.int16
: 16 位有符号整数(-32_768
到 32_767
)。
class numpy.intc
有符号整数类型,与 C int
兼容。
字符编码:
'i'
在这个平台上的别名(Linux x86_64):
numpy.int32
: 32 位有符号整数(-2_147_483_648
到 2_147_483_647
)。
class numpy.int_
有符号整数类型,与 Python int 和 C long
兼容。
字符编码:
'l'
在这个平台上的别名(Linux x86_64):
numpy.int64
: 64 位有符号整数(-9_223_372_036_854_775_808
到 9_223_372_036_854_775_807
)。
在这个平台上的别名(Linux x86_64):
numpy.intp
: 足够大以容纳指针的有符号整数,与 C intptr_t
兼容。
class numpy.longlong
有符号整数类型,与 C long long
兼容。
字符编码:
'q'
无符号整数类型
class numpy.unsignedinteger
所有无符号整数标量类型的抽象基类。
class numpy.ubyte
无符号整数类型,与 C unsigned char
兼容。
字符编码:
'B'
在这个平台上的别名(Linux x86_64):
numpy.uint8
: 8 位无符号整数(0
到 255
)。
class numpy.ushort
无符号整数类型,与 C unsigned short
兼容。
字符编码:
'H'
在这个平台上的别名(Linux x86_64):
numpy.uint16
: 16 位无符号整数(0
到 65_535
)。
class numpy.uintc
无符号整数类型,与 C unsigned int
兼容。
字符编码:
'I'
在这个平台上的别名(Linux x86_64):
numpy.uint32
: 32 位无符号整数(0
到 4_294_967_295
)。
class numpy.uint
无符号整数类型,与 C unsigned long
兼容。
字符编码:
'L'
在此平台上的别名(Linux x86_64):
numpy.uint64
:64 位无符号整数(0
到18_446_744_073_709_551_615
)。
在此平台上的别名(Linux x86_64):
numpy.uintp
:足够大以适应指针的无符号整数,与 C uintptr_t
兼容。
class numpy.ulonglong
有符号整数类型,与 C unsigned long long
兼容。
字符编码:
'Q'
不精确类型
class numpy.inexact
所有数值标量类型的抽象基类,其值的表示(可能)不精确,如浮点数。
注意
使用最少的十进制数字打印不精确标量,以区分其值与同一数据类型的其他值,通过谨慎的四舍五入。参见format_float_positional
和format_float_scientific
的unique
参数。
这意味着具有相同二进制值但数据类型不同精度的变量可能显示不同:
>>> f16 = np.float16("0.1")
>>> f32 = np.float32(f16)
>>> f64 = np.float64(f32)
>>> f16 == f32 == f64
True
>>> f16, f32, f64
(0.1, 0.099975586, 0.0999755859375)
请注意,这些浮点数中没有一个保存精确值(\frac{1}{10});f16
打印为0.1
,因为它尽可能接近该值,而其他类型不会,因为它们具有更高的精度,因此具有更接近的值。
相反,近似相同十进制值的不同精度的浮点标量可能比较不相等,尽管打印相同:
>>> f16 = np.float16("0.1")
>>> f32 = np.float32("0.1")
>>> f64 = np.float64("0.1")
>>> f16 == f32 == f64
False
>>> f16, f32, f64
(0.1, 0.1, 0.1)
浮点类型
class numpy.floating
所有浮点标量类型的抽象基类。
class numpy.half
半精度浮点数类型。
字符编码:
'e'
在此平台上的别名(Linux x86_64):
numpy.float16
:16 位精度浮点数类型:符号位,5 位指数,10 位尾数。
class numpy.single
单精度浮点数类型,与 C float
兼容。
字符编码:
'f'
在此平台上的别名(Linux x86_64):
numpy.float32
:32 位精度浮点数类型:符号位,8 位指数,23 位尾数。
class numpy.double(x=0, /)
双精度浮点数类型,与 Python float和 C double
兼容。
字符编码:
'd'
别名:
numpy.float_
在此平台上的别名(Linux x86_64):
numpy.float64
:64 位精度浮点数类型:符号位,11 位指数,52 位尾数。
class numpy.longdouble
扩展精度浮点数类型,与 C long double
兼容,但不一定与 IEEE 754 四倍精度兼容。
字符编码:
'g'
别名:
numpy.longfloat
在此平台上的别名(Linux x86_64):
numpy.float128
:128 位扩展精度浮点数类型。
复数浮点类型
class numpy.complexfloating
由浮点数组成的所有复数标量类型的抽象基类。
class numpy.csingle
由两个单精度浮点数组成的复数类型。
字符编码:
'F'
别名:
numpy.singlecomplex
在此平台上的别名(Linux x86_64):
numpy.complex64
:由两个 32 位精度浮点数组成的复数类型。
class numpy.cdouble(real=0, imag=0)
由两个双精度浮点数组成的复数类型,与 Python complex兼容。
字符编码:
'D'
别名:
numpy.cfloat
别名:
numpy.complex_
在此平台上的别名(Linux x86_64):
numpy.complex128
:由两个 64 位精度浮点数组成的复数类型。
class numpy.clongdouble
由两个扩展精度浮点数组成的复数类型。
字符编码:
'G'
别名:
numpy.clongfloat
别名:
numpy.longcomplex
在此平台上的别名(Linux x86_64):
numpy.complex256
:由两个 128 位扩展精度浮点数组成的复数类型。
浮点数类型
class numpy.floating
所有浮点数标量类型的抽象基类。
class numpy.half
半精度浮点数类型。
字符编码:
'e'
在此平台上的别名(Linux x86_64):
numpy.float16
:16 位精度浮点数类型:符号位,5 位指数,10 位尾数。
class numpy.single
单精度浮点数类型,与 C 中的float
兼容。
字符编码:
'f'
在此平台上的别名(Linux x86_64):
numpy.float32
: 32 位精度浮点数类型:符号位,8 位指数,23 位尾数。
class numpy.double(x=0, /)
双精度浮点数类型,与 Python float和 C 中的double
兼容。
字符编码:
'd'
别名:
numpy.float_
在此平台上的别名(Linux x86_64):
numpy.float64
:64 位精度浮点数类型:符号位,11 位指数,52 位尾数。
class numpy.longdouble
扩展精度浮点数类型,与 C 中的long double
兼容,但不一定与 IEEE 754 四倍精度兼容。
字符编码:
'g'
别名:
numpy.longfloat
在此平台上的别名(Linux x86_64):
numpy.float128
:128 位扩展精度浮点数类型。
复数浮点数类型
class numpy.complexfloating
所有由浮点数组成的复数标量类型的抽象基类。
class numpy.csingle
由两个单精度浮点数组成的复数类型。
字符编码:
'F'
别名:
numpy.singlecomplex
在此平台上的别名(Linux x86_64):
numpy.complex64
:由两个 32 位精度浮点数组成的复数类型。
class numpy.cdouble(real=0, imag=0)
由两个双精度浮点数组成的复数类型,与 Python 的complex兼容。
字符编码:
'D'
别名:
numpy.cfloat
别名:
numpy.complex_
在这个平台上的别名(Linux x86_64):
numpy.complex128
:由 2 个 64 位精度浮点数组成的复数类型。
class numpy.clongdouble
由两个扩展精度浮点数组成的复数类型。
字符编码:
'G'
别名:
numpy.clongfloat
别名:
numpy.longcomplex
在这个平台上的别名(Linux x86_64):
numpy.complex256
:由 2 个 128 位扩展精度浮点数组成的复数类型。
其他类型
class numpy.bool_
存储为字节的布尔类型(True 或 False)。
警告
bool_
类型不是int_
类型的子类(bool_
甚至不是一个数字类型)。这与 Python 默认实现的bool
作为int
的子类不同。
字符编码:
'?'
class numpy.datetime64
如果从 64 位整数创建,它表示从1970-01-01T00:00:00
的偏移量。如果从字符串创建,字符串可以是 ISO 8601 日期或日期时间格式。
>>> np.datetime64(10, 'Y')
numpy.datetime64('1980')
>>> np.datetime64('1980', 'Y')
numpy.datetime64('1980')
>>> np.datetime64(10, 'D')
numpy.datetime64('1970-01-11')
更多信息请参见日期时间和时间增量。
字符编码:
'M'
class numpy.timedelta64
以 64 位整数存储的时间增量。
更多信息请参见日期时间和时间增量。
字符编码:
'm'
class numpy.object_
任何 Python 对象。
字符编码:
'O'
注意
实际存储在对象数组中的数据(即,具有 dtype object_
的数组)是对 Python 对象的引用,而不是对象本身。因此,对象数组的行为更像通常的 Python lists
,即它们的内容不一定是相同的 Python 类型。
对象类型也很特殊,因为包含object_
项的数组在访问项时不会返回一个object_
对象,而是返回数组项引用的实际对象。
以下数据类型是灵活的:它们没有预定义的大小,它们描述的数据可以在不同数组中具有不同的长度。(在字符编码中,#
是一个整数,表示数据类型包含多少个元素。)
class numpy.flexible
所有没有预定义长度的标量类型的抽象基类。这些类型的实际大小取决于特定的np.dtype实例化。
class numpy.character
所有字符字符串标量类型的抽象基类。
class numpy.bytes_
一个字节字符串。
在数组中使用时,此类型会剥离尾随的空字节。
字符代码:
'S'
别名:
numpy.string_
class numpy.str_
一个 Unicode 字符串。
此类型会剥离尾随的空代码点。
>>> s = np.str_("abc\x00")
>>> s
'abc'
与内置str不同,它支持缓冲区协议,将其内容公开为 UCS4:
>>> m = memoryview(np.str_("abc"))
>>> m.format
'3w'
>>> m.tobytes()
b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
字符代码:
'U'
别名:
numpy.unicode_
class numpy.void(length_or_data, /, dtype=None)
创建一个新的结构化或非结构化的空标量。
参数:
length_or_dataint,类似数组,类似字节,对象
具有多重含义之一(请参阅注释)。非结构化空的长度或字节数据。或者,当提供dtype
时,要存储在新标量中的数据。这可以是类似数组的,如果是这种情况,则可能返回一个数组。
dtypedtype,可选
如果提供了新标量的 dtype。此 dtype 必须是“void”dtype(即结构化或非结构化的 void,请参阅结构化数据类型)。
..versionadded:: 1.24
注意
出于历史原因,以及因为空标量可以表示任意字节数据和结构化数据类型,空构造函数有三种调用约定:
-
np.void(5)
创建一个填充有五个\0
字节的dtype="V5"
标量。5 可以是 Python 或 NumPy 整数。 -
np.void(b"bytes-like")
从字节字符串创建一个空标量。dtype itemsize 将匹配字节字符串长度,在这里是"V10"
。 -
当传递
dtype=
时,调用与数组创建大致相同。但是,返回的是一个空标量而不是数组。
请参阅显示所有三种不同约定的示例。
示例
>>> np.void(5)
void(b'\x00\x00\x00\x00\x00')
>>> np.void(b'abcd')
void(b'\x61\x62\x63\x64')
>>> np.void((5, 3.2, "eggs"), dtype="i,d,S5")
(5, 3.2, b'eggs') # looks like a tuple, but is `np.void`
>>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
(3, 3) # looks like a tuple, but is `np.void`
字符代码:
'V'
警告
请参阅关于字符串类型的说明。
数值兼容性:如果您在 Numeric 代码中使用了旧的类型代码字符(这从未被推荐过),则需要将其中一些更改为新字符。特别是,需要更改的是 c -> S1
,b -> B
,1 -> b
,s -> h
,w -> H
和 u -> I
。这些更改使类型字符约定更加一致,与其他 Python 模块(如struct
模块)一致。
大小别名
除了它们(主要)是 C 派生的名称之外,整数、浮点数和复数数据类型也可以使用位宽约定,以便始终可以确保正确大小的数组。还提供了两个别名(numpy.intp
和 numpy.uintp
),指向足够大以容纳 C 指针的整数类型。
numpy.int8
numpy.int16
numpy.int32
numpy.int64
有指定位数的带符号整数类型的别名(其中之一是numpy.byte
,numpy.short
,numpy.intc
,numpy.int_
和numpy.longlong
)。
与 C99 的int8_t
,int16_t
,int32_t
和int64_t
兼容。
numpy.uint8
numpy.uint16
numpy.uint32
numpy.uint64
有指定位数的无符号整数类型的别名(其中之一是numpy.ubyte
,numpy.ushort
,numpy.uintc
,numpy.uint
和numpy.ulonglong
)。
与 C99 的uint8_t
,uint16_t
,uint32_t
和uint64_t
兼容。
numpy.intp
与指针大小相同的带符号整数类型的别名(其中之一是numpy.byte
,numpy.short
,numpy.intc
,numpy.int_
和np.longlong)。
与 C intptr_t
兼容。
字符编码:
'p'
numpy.uintp
与指针大小相同的无符号整数类型的别名(其中之一是numpy.ubyte
,numpy.ushort
,numpy.uintc
,numpy.uint
和np.ulonglong)。
与 C uintptr_t
兼容。
字符编码:
'P'
numpy.float16
half
的别名
numpy.float32
single
的别名
numpy.float64
double
的别名
numpy.float96
numpy.float128
numpy.longdouble
的别名,根据其位数命名。这些别名的存在取决于平台。
numpy.complex64
csingle
的别名
numpy.complex128
cdouble
的别名
numpy.complex192
numpy.complex256
numpy.clongdouble
的别名,根据其位数命名。这些别名的存在取决于平台。
其他别名
前两个别名类似于内置类型的名称,与bool_
,int_
,str_
,bytes_
和object_
的风格相似:
numpy.float_
double
的别名
numpy.complex_
cdouble
的别名
一些使用扩展精度浮点数和复数的替代命名约定:
numpy.longfloat
longdouble
的别名
numpy.singlecomplex
csingle
的别名
numpy.cfloat
cdouble
的别名
numpy.longcomplex
clongdouble
的别名
numpy.clongfloat
clongdouble
的别名
以下别名源自 Python 2,建议不要在新代码中使用。
numpy.string_
bytes_
的别名
numpy.unicode_
str_
的别名
属性
数组标量对象具有array priority
为NPY_SCALAR_PRIORITY
(-1,000,000.0)。它们还没有(但)具有ctypes
属性。否则,它们与数组共享相同的属性:
generic.flags |
标志的整数值。 |
---|---|
generic.shape |
数组维度的元组。 |
generic.strides |
每个维度中的字节步长元组。 |
generic.ndim |
数组维度的数量。 |
generic.data |
数据起始指针。 |
generic.size |
gentype 中元素的数量。 |
generic.itemsize |
一个元素的长度(以字节为单位)。 |
generic.base |
与相应数组属性相同的标量属性。 |
generic.dtype |
获取数组数据描述符。 |
generic.real |
标量的实部。 |
generic.imag |
标量的虚部。 |
generic.flat |
标量的一维视图。 |
generic.T |
与相应数组属性相同的标量属性。 |
generic.__array_interface__ |
数组协议:Python 端 |
generic.__array_struct__ |
数组协议:结构 |
generic.__array_priority__ |
数组优先级。 |
generic.__array_wrap__ |
sc.array_wrap(obj) 从数组返回标量 |
索引
另请参阅
索引例程,数据类型对象(dtype)
数组标量可以像 0 维数组一样进行索引:如果x是一个数组标量,
-
x[()]
返回数组标量的副本 -
x[...]
返回一个 0 维ndarray
-
x['field-name']
返回字段field-name中的数组标量。(x 可能具有字段,例如,当它对应于结构化数据类型时。)
方法
数组标量具有与数组完全相同的方法。这些方法的默认行为是内部将标量转换为等效的 0 维数组,并调用相应的数组方法。此外,对数组标量的数学运算被定义为设置和用于解释结果的硬件标志与 ufunc 相同,因此 ufunc 上使用的错误状态也会传递到数组标量上的数学运算中。
以下是上述规则的例外情况:
generic.__array__ |
sc.array(dtype) 从指定 dtype 的标量返回 0 维数组 |
---|---|
generic.__array_wrap__ |
sc.array_wrap(obj) 从数组返回标量 |
generic.squeeze |
与相应数组属性相同的标量方法。 |
generic.byteswap |
与相应数组属性相同的标量方法。 |
generic.__reduce__ |
pickle 的辅助函数。 |
generic.__setstate__ |
|
generic.setflags |
与相应数组属性相同的标量方法。 |
用于类型的实用方法:
number.__class_getitem__ (item, /) |
返回围绕number 类型的参数化包装器。 |
---|
定义新类型
有两种有效的方法来定义一个新的数组标量类型(除了从内置标量类型组合结构化类型 dtypes):一种方法是简单地子类化ndarray
并重写感兴趣的方法。这在一定程度上可以工作,但在内部,某些行为是由数组的数据类型固定的。要完全自定义数组的数据类型,您需要定义一个新的数据类型,并将其注册到 NumPy 中。这样的新类型只能在 C 中定义,使用 NumPy C-API。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
2021-06-24 如何评价「施一公请辞清华大学副校长,全职执掌西湖大学」?你如何看待西湖大学的发展前景?