注:因为Numpy的官方文档是全英文的,本篇文章也基本使用英文写作,部分知识、注释有中文。
1. Quickstart Tutorial
1.1 Prerequisites
1.2 The Basics
-
ndarray.ndim
The number of the axis(dimensions) of the array
-
ndarray.shape
The dimension of a array. If a matrix with nrows and mcolumns, the shape will be (n,m)
-
ndarray.size
The total number of elements of the array. This is equal to the product of the elements of shape
.
-
ndarray.dtype
An object describing the type of the elements in the array.
-
ndarray.itemsize
The size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8).
-
ndarray.data
The buffer containing actual elements of the array.
-
# Example
>>> 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.itemsize
8
>>> a.dtype
dtype('int64')
>>> a.dtype.name
'int64'
>>> a.size
15
>>> a.ndim
2
>>> type(a)
<class 'numpy.ndarray'>
1.3 Array Creation
1)Create an array from a regular Python list or tuple using the array function
-
Example
>>> import numpy as np
>>> a = np.array([2,3,4])
>>> a
array([2, 3, 4])
>>> a.dtype.name
'int64'
>>> a.shape
(3,)
>>> b = np.array([1.1, 2.2, 3.3])
>>> b
array([1.1, 2.2, 3.3])
>>> b.dtype.name
'float64'
注意⚠️
>>> a = np.array([1,2,3,4]) # Right
>>> a = np.array(1,2,3,4) # Wrong
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
a = np.array(1,2,3,4)
ValueError: only 2 non-keyword arguments accepted
2)Create an zeros or ones or empty array
>>> np.zeros((2,3))
array([[0., 0., 0.],
[0., 0., 0.]])
>>> np.ones((2,3))
array([[1., 1., 1.],
[1., 1., 1.]])
>>> np.empty((3,4))
array([[0.00000000e+000, 0.00000000e+000, 6.91691904e-323,
nan],
[4.35521702e+266, 2.16707129e+059, 2.35999090e-311,
8.59107696e+115],
[6.67644117e+151, 1.91084646e+214, 1.16034643e-308,
3.65093134e+233]])
3)Create array of range function instead of lists
>>> np.arange(10,30,5)
array([10, 15, 20, 25])
>>> np.arange(10,50,5)
array([10, 15, 20, 25, 30, 35, 40, 45])
4)Create lots of points rather than range, for its floating precision
>>> from numpy import pi
>>> np.linspace(0,2,9)
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
>>> # create 9 numbers from 0 to 2
>>> x = np.linspace(0, 2*pi, 100)
>>> f = np.sin(x)
1.4 Basic Operations
1)’+’ and ‘-‘ is the same with linear algebra
2)multiply
>>> A = np.array([[1,1], [0,1]])
>>> B = np.array([[2,0], [3,4]])
>>> A
array([[1, 1],
[0, 1]])
>>> B
array([[2, 0],
[3, 4]])
>>> A*B # *号乘法只是对应坐标的点相乘
array([[2, 0],
[0, 4]])
>>> np.dot(A,B) # 表示矩阵乘法,在Python3.5+, 可使用’@’代替
array([[5, 4],
[3, 4]])
>>> A@B
array([[5, 4],
[3, 4]])
1.5 Universal Functions
Numpy provides mathematical functions, such as sin, cos, exp, pow and etc..
1.6 Indexing, Slicing and Iterating
1)One dimensional arrays
>>> a = np.arange(10)**3
>>> a
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729])
>>> a[1]
1
>>> a[2]
8
>>> a[:5]
array([ 0, 1, 8, 27, 64])
>>> a[:6:2] = -1000
>>> a
array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512,
729])
>>> # equivalent set from a[0] - a[6] every 2 steps as -1000
>>> a[::-1]
array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1,
-1000])
2)Multidimensional arrays
>>> import numpy as np
>>> def f(x,y):
return x*10+y
>>> 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[:5,1]
array([ 1, 11, 21, 31, 41])
>>> b[-1]
array([40, 41, 42, 43])
>>> c = np.array([[[0,1,2], [10,12,13]],])
>>>
>>> c
array([[[ 0, 1, 2],
[10, 12, 13]]])
>>> c = np.array([[[0,1,2], [10,12,13]],[[100,101,102],[110,112,113]]])
>>> c
array([[[ 0, 1, 2],
[ 10, 12, 13]],
[[100, 101, 102],
[110, 112, 113]]])
>>> c.shape
(2, 2, 3)
>>> c[0,:,:]
array([[ 0, 1, 2],
[10, 12, 13]])
>>> c[1,1,2]
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]
>>> 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
1.7 Shape Manipulation
1)Changing the shape of an array
>>> a = np.array([[-1.2,3.5,6.5], [-10.9,4.6,-2.3]])
>>> a
array([[ -1.2, 3.5, 6.5],
[-10.9, 4.6, -2.3]])
>>> b = np.floor(a)
>>> b
array([[ -2., 3., 6.],
[-11., 4., -3.]])
>>> c = np.ceil(a)
>>> c
array([[ -1., 4., 7.],
[-10., 5., -2.]])
# a.T求的事矩阵a的转置
# 转置是把矩阵a的列用行来表示,行用列来表示
>>> aT = a.T
>>> aT
array([[ -1.2, -10.9],
[ 3.5, 4.6],
[ 6.5, -2.3]])
>>> a.shape
(2, 3)
# reshape()指的转换矩阵a的行数和列数
>>> a.reshape(3,2)
array([[ -1.2, 3.5],
[ 6.5, -10.9],
[ 4.6, -2.3]])
注意⚠️
np.floor()是向小的那方靠近,即中文意思向地板靠近;
np.ceil()是向大的那方靠近,即中文意思向天花板靠近。
2)Stacking different array together
# 在行上合并矩阵np.hstack(a,b)
# 指的是将b合并在a后,因此二者调换的话,结果不同
>>> np.hstack((a,b))
array([[1, 1, 1, 2, 3],
[2, 2, 4, 5, 6],
[3, 3, 7, 8, 9]])
>>> np.hstack((b,a))
array([[1, 2, 3, 1, 1],
[4, 5, 6, 2, 2],
[7, 8, 9, 3, 3]])
# 在列上合并矩阵np.vstack(a,b)
# 因为在列上进行合并,因此a和b的行数和列数必须相同,不然会报错
# 转换成程序,即a.shape == b.shape
# 下面进行验证
>>> d = np.ones((3,3))
>>> d
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> np.vstack((b,d))
array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> np.vstack((d,b))
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
# np.column_stack可以在列上进行合并,同np.vstack()
>>> a = np.array((1,2,3))
>>> b = np.array((4,5,6))
>>> np.column_stack((a,b))
array([[1, 4],
[2, 5],
[3, 6]])
3)Spitting one array into several smaller ones
-
np.hsplit(): split by horizontal axis
-
np.vsplit(): split by vertical axis
>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[4., 8., 7., 4., 9., 6., 8., 2., 9., 4., 4., 1.],
[5., 3., 6., 2., 4., 3., 8., 1., 8., 9., 8., 5.]])
>>> np.hsplit(a,3)
[array([[4., 8., 7., 4.],
[5., 3., 6., 2.]]), array([[9., 6., 8., 2.],
[4., 3., 8., 1.]]), array([[9., 4., 4., 1.],
[8., 9., 8., 5.]])]
>>> np.hsplit(a,3)[0]
array([[4., 8., 7., 4.],
[5., 3., 6., 2.]])
1.8 Copies and Views
1)No copy at all
-
Simple assignments make no copy of array objects or of their data
>>> a = np.arange(12)
>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> b = a
>>> b is a
True
>>> a.shape
(12,)
>>> b.shape
(12,)
>>> b.shape = 3,4
>>> a.shape
(3, 4)
-
Unique identifier
>>> def f(x):
print(id(x))
>>> id(a)
4616636496
>>> f(a)
4616636496
2)View or shallow copy
-
Different array objects can share the same data. The view method creates a new array object that looks at the same data.
>>> c = a.view()
>>> c is a
False
>>> c.base is a
True
>>> c.flags.owndata
False
>>> c.shape
(3, 4)
>>> c.shape = 2,6 # a’s shape doesn’t change
>>> a.shape
(3, 4)
>>> c
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
>>> c[0,4]
4
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> c[0,4] = 1234 # a’s data change
>>> a
array([[ 0, 1, 2, 3],
[1234, 5, 6, 7],
[ 8, 9, 10, 11]])
-
Slicing an array
>> s = a[:,1:3]
>>> s
array([[ 1, 2],
[ 5, 6],
[ 9, 10]])
>>> s[:] = 10
>>> s
array([[10, 10],
[10, 10],
[10, 10]])
>>> a
array([[ 0, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])
>>> s.base is a
True
3)Deep copy
>>> d = a.copy()
>>> d
array([[ 0, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])
>>> d is a
False
>>> d.base is a # d doesn’t share anything with a
False
>>> d[0,0] = 9999
>>> d
array([[9999, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])
>>> a
array([[ 0, 10, 10, 3],
[1234, 10, 10, 7],
[ 8, 10, 10, 11]])