基础知识 | 快速入门教程 |《numpy 中文文档》| python 技术论坛-江南app体育官方入口
numpy 的主要对象是同类的多维数组。它是一个元素表(通常为数字),所有相同的类型,由一元组非负整数编制索引。在 numpy 维度中称为坐标轴
。
例如,[1, 2, 1]
在 3d 空间中点坐标有一个轴。该轴有 3 个元素,因此我们说它的长度为 3。在下面的示例中,数组有 2 个轴。第一个轴的长度为 2,第二个轴的长度为 3。
[[ 1., 0., 0.],
[ 0., 1., 2.]]
numpy 的数组类称为ndarray
。array
也被称为别名。请注意,numpy.array
与标准 python 库类array.array
不同,该类只处理一维数组,并且提供的功能较少。ndarray
对象的更重要的属性是:
- ndarray.ndim:数组的轴(尺寸)数。
- ndarray.shape: 数组的尺寸。这是一个整数元组,指示每个维度中数组的大小。对于包含n 行和 m 列的矩阵,将为 。因此,元组的长度是轴的数量。
- ndarray.size: 数组的元素总数。它等于
.shape
的乘积。 - ndarray.dtype: 描述数组中元素类型的对象。可以使用标准 python 类型创建或指定 dtype。此外,numpy 还提供自己的类型。numpy. int32 , numpy. int16 和 numpy. float64 是一些示例。
- ndarray.itemsize: 数组的每个元素的大小(以字节为单位)。例如,float64 类型元素数组为 8( 64/8),而 complex32 类型为 4( 32/8)。它等效于
ndarray.dtype.itemsize
- ndarray.data: 包含数组的实际元素的缓冲区。通常,我们不需要使用此属性,因为我们将使用索引工具访问数组中的元素。
示例
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.itemsize
8
>>> a.size
15
>>> type(a)
<class 'numpy.ndarray'>
>>> b = np.array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
<class 'numpy.ndarray'>
数组创建
创建数组的方法有多种。
例如,您可以使用array
函数从常规 python 列表或元组创建数组。生成的数组的类型从序列中元素的类型推断出来。
>>> import numpy as np
>>> a = np.array([2,3,4])
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int64')
>>> b = np.array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64')
一个常见的错误是使用多个参数调用数组,而不是提供单个序列作为参数。
>>> a = np.array(1,2,3,4) # wrong
traceback (most recent call last):
...
typeerror: array() takes from 1 to 2 positional arguments but 4 were given
>>> a = np.array([1,2,3,4]) # right
array
将序列序列转换为二维数组,将序列序列转换为三维数组,等等。
>>> b = np.array([(1.5,2,3), (4,5,6)])
>>> b
array([[1.5, 2. , 3. ],
[4. , 5. , 6. ]])
也可以在创建时显式指定数组的类型:
>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )
>>> c
array([[1.0.j, 2.0.j],
[3.0.j, 4.0.j]])
通常,数组的元素最初是未知的,但其大小是已知的。因此,numpy 提供了多个函数来创建具有初始占位符内容的数组。这些最小化了增加阵列的必要性,这是一个昂贵的操作。
zeros
函数创建一个满零的数组,ones
函数创建一个满1的数组,empty
函数创建一个数组,其初始内容是随机的,取决于内存的状态。默认情况下,创建的数组的 dtype 为float64
。
>>> np.zeros((3, 4))
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
>>> np.ones( (2,3,4), dtype=np.int16 ) # dtype can also be specified
array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]], dtype=int16)
>>> np.empty( (2,3) ) # uninitialized
array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260], # may vary
[ 5.30498948e-313, 3.14673309e-307, 1.00000000e 000]])
要创建数字序列,numpy 提供类似于 python 内置 的函数,但返回数组。arange``range
>>> np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> np.arange( 0, 2, 0.3 ) # it accepts float arguments
array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
当与浮点参数一起使用时,由于浮点精度有限,通常无法预测获得的元素数。因此,通常最好使用接收的函数作为参数来表示我们想要的元素数,而不是步骤:arange``linspace
>>> from numpy import pi
>>> np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
>>> x = np.linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points
>>> f = np.sin(x)
另请参阅
,
,
numpy.random.generator.rand
numpy.random.generator.randn
打印阵列
打印数组时,numpy 以类似于嵌套列表的方式显示它,但具有以下布局:
- 最后一个轴从左到右打印,
- 倒数第二个从上到下打印,
- 其余部分也从上到下打印,每个切片与下一个切片以空行分隔。
然后,一维数组打印为行,标的作为矩阵,三维数组作为矩阵列表。
>>> a = np.arange(6) # 1d array
>>> print(a)
[0 1 2 3 4 5]
>>>
>>> b = np.arange(12).reshape(4,3) # 2d array
>>> print(b)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
>>>
>>> c = np.arange(24).reshape(2,3,4) # 3d array
>>> print(c)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
请参阅文,获取 有关 的更多详细信息。reshape
如果数组太大而无法打印,numpy 会自动跳过数组的中心部分,只打印角:
>>> print(np.arange(10000))
[ 0 1 2 ... 9997 9998 9999]
>>>
>>> print(np.arange(10000).reshape(100,100))
[[ 0 1 2 ... 97 98 99]
[ 100 101 102 ... 197 198 199]
[ 200 201 202 ... 297 298 299]
...
[9700 9701 9702 ... 9797 9798 9799]
[9800 9801 9802 ... 9897 9898 9899]
[9900 9901 9902 ... 9997 9998 9999]]
若要禁用此行为并强制 numpy 打印整个阵列,可以使用 更改打印选项。set_printoptions
>>> np.set_printoptions(threshold=sys.maxsize) # sys module should be imported
基本操作
数组上的算术运算符应用元素。将创建一个新数组,并填充结果。
>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])
>>> a<35
array([ true, true, false, false])
与许多矩阵语言不同,产品运算符在 numpy 数组中按元素运行。矩阵产品可以使用运算符(在 python >=3.5)或函数或方法执行:* @ dot
>>> a = np.array( [[1,1],
... [0,1]] )
>>> b = np.array( [[2,0],
... [3,4]] )
>>> a * b # elementwise product
array([[2, 0],
[0, 4]])
>>> a @ b # matrix product
array([[5, 4],
[3, 4]])
>>> a.dot(b) # another matrix product
array([[5, 4],
[3, 4]])
某些操作(如 和 )就地修改现有数组,而不是创建新数组。 = *=
>>> rg = np.random.default_rng(1) # create instance of default random number generator
>>> a = np.ones((2,3), dtype=int)
>>> b = rg.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
[3, 3, 3]])
>>> b = a
>>> b
array([[3.51182162, 3.9504637 , 3.14415961],
[3.94864945, 3.31183145, 3.42332645]])
>>> a = b # b is not automatically converted to integer type
traceback (most recent call last):
...
numpy.core._exceptions.ufunctypeerror: cannot cast ufunc 'add' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
当使用不同类型的数组时,生成的数组的类型对应于更常规或更精确的数组(一种称为向上转换的行为)。
>>> a = np.ones(3, dtype=np.int32)
>>> b = np.linspace(0,pi,3)
>>> b.dtype.name
'float64'
>>> c = ab
>>> c
array([1. , 2.57079633, 4.14159265])
>>> c.dtype.name
'float64'
>>> d = np.exp(c*1j)
>>> d
array([ 0.540302310.84147098j, -0.841470980.54030231j,
-0.54030231-0.84147098j])
>>> d.dtype.name
'complex128'
许多一元操作(如计算数组中所有元素的总和)都作为类的方法实现。ndarray
>>> a = rg.random((2,3))
>>> a
array([[0.82770259, 0.40919914, 0.54959369],
[0.02755911, 0.75351311, 0.53814331]])
>>> a.sum()
3.1057109529998157
>>> a.min()
0.027559113243068367
>>> a.max()
0.8277025938204418
默认情况下,这些操作应用于数组,就像它是数字列表一样,无论其形状如何。但是,通过指定参数,可以沿数组的指定轴应用操作:axis
>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>>
>>> b.sum(axis=0) # sum of each column
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1) # min of each row
array([0, 4, 8])
>>>
>>> b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38]])
通用功能
numpy 提供熟悉的数学函数,如 sin、cos 和 exp。在 numpy 中,这些称为”通用函数”()。在 numpy 中,这些函数在数组上按元素操作,生成数组作为输出。ufunc
>>> b = np.arange(3)
>>> b
array([0, 1, 2])
>>> np.exp(b)
array([1. , 2.71828183, 7.3890561 ])
>>> np.sqrt(b)
array([0. , 1. , 1.41421356])
>>> c = np.array([2., -1., 4.])
>>> np.add(b, c)
array([2., 0., 6.])
另请参阅
, 任何, ,, , ,, 暨,,,,,, ,,,,,, 非零, 外部 排序,sum, 置, var ,
索引、切片和索引
一维数组可以进行索引、切片和重复,就像列表python 序列一样。
>>> a = np.arange(10)**3
>>> a
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
# equivalent to a[0:6:2] = 1000;
# from start to position 6, exclusive, set every 2nd element to 1000
>>> a[:6:2] = 1000
>>> a
array([1000, 1, 1000, 27, 1000, 125, 216, 343, 512, 729])
>>> a[ : :-1] # reversed a
array([ 729, 512, 343, 216, 125, 1000, 27, 1000, 1, 1000])
>>> for i in a:
... print(i**(1/3.))
...
9.999999999999998
1.0
9.999999999999998
3.0
9.999999999999998
4.999999999999999
5.999999999999999
6.999999999999999
7.999999999999999
8.999999999999998
多维数组可以每个轴有一个索引。这些索引以用逗号分隔的元组给出:
>>> def f(x,y):
... return 10*xy
...
>>> b = np.fromfunction(f,(5,4),dtype=int)
>>> b
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
>>> b[2,3]
23
>>> b[0:5, 1] # each row in the second column of b
array([ 1, 11, 21, 31, 41])
>>> b[ : ,1] # equivalent to the previous example
array([ 1, 11, 21, 31, 41])
>>> b[1:3, : ] # each column in the second and third row of b
array([[10, 11, 12, 13],
[20, 21, 22, 23]])
当提供的索引少于轴数时,缺少的索引将被视为完整切片:
>>> b[-1] # the last row. equivalent to b[-1,:]
array([40, 41, 42, 43])
括号内的表达式被视为后跟任意多个实例来表示剩余的轴。numpy还允许您使用点来表示。b[i]i:b[i,...]
dots() 表示生成完整索引元组所需的多冒号。例如,如果是具有 5 个轴的数组,则...x
x[1,2,...]
等效于x[1,2,:,:,:]
x[...,3]
和x[:,:,:,:,3]
x[4,...,5,:]
和x[4,:,:,5,:]
>>> c = np.array( [[[ 0, 1, 2], # a 3d array (two stacked 2d arrays)
... [ 10, 12, 13]],
... [[100,101,102],
... [110,112,113]]])
>>> c.shape
(2, 2, 3)
>>> c[1,...] # same as c[1,:,:] or c[1]
array([[100, 101, 102],
[110, 112, 113]])
>>> c[...,2] # same as c[:,:,2]
array([[ 2, 13],
[102, 113]])
迭代多维数组是在第一个轴上完成的:
>>> for row in b:
... print(row)
...
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]
但是,如果想对数组中的每个元素执行操作,可以使用属性,该属性是数组中所有元素的迭代器:flat
>>> for element in b.flat:
... print(element)
...
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43
另请参阅