The study notes python numpy

First, the concept:
NumPy (Numerical Python) is an extension library Python language, supports a number of dimensions of the array and matrix operations, in addition, it provides a lot of math library for array operations.
NumPy is running very fast math library, mainly for computing array, comprising:

			一个强大的N维数组对象 ndarray
			广播功能函数
			整合 C/C++/Fortran 代码的工具
			线性代数、傅里叶变换、随机数生成等功能

Second, the code Explanation
1. array property
np.array statement is defined array numpy

Attributes Explanation
ndattay.ndim Rank number, i.e. the number or dimensions of shaft
ndattay.shape Dimension of an array, for the matrix, n rows and n columns
ndattay.size The total number of array elements, the shape corresponds to the value of the n * m
ndattay.dtype Object element type ndarray
import numpy as np

array = np.array([[1,2,3],[4,5,6]])   #定义矩阵
print(array)
print("number of dim:",array.ndim )     # 维度
print('shape:', array.shape)            # 形状,几行几列
print('size:',array.size)               # 元素个数

result:

[[1 2 3]
 [4 5 6]]
number of dim: 2
shape: (2, 3)
size: 6

2. Create Array
np.array ([2,25,4], dtype = np.float32)
when creating Array, plus dtype defined data type attribute can
numeric type dtype numpy fact an instance of the object, and corresponds to a unique characters, including np.bool_, np.int32, np.float32, and so on.

aa = np.array([2,25,4],dtype=np.float32)          # dtype 定义数据类型
print(aa.dtype)

result:

float32

Defined matrix

a = np.array([[1,56,2],                            # 定义矩阵
              [4,5,6]])
print(a)

result:

[[ 1 56  2]
 [ 4  5  6]]

The definition of all-zero matrix

b = np.zeros((3,4))                        # 全零的矩阵
print(b)

result:

[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

Define the matrix of all ones

c = np.ones((3,4),dtype=np.int16)          # 全1的矩阵
print(c)

result:

[[1 1 1 1]
 [1 1 1 1]
 [1 1 1 1]]

Define the empty matrix

Nothing matrix, in fact, its value is close to 0

d = np.empty((3,4))          # 什么都没有的矩阵,各项值近似于零
print(d)

result;

[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

Definition list

Definition from 10 to 20, the number of steps of the list 2, and reshape the shape of the matrix may be redefined

e = np.arange(10,20,2)         # 定义从10到20,步数为2的列表
print(e)
f = np.arange(12).reshape((3,4))    # reshape 重新定义矩阵的形状 行和列
print(f)

result:

[10 12 14 16 18]

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Definition segment length
definition segment length, and arange very similar, but the steps into the third parameter is divided into many parts, i.e. the number of sets of data.
It can be changed in shape by reshape.

g = np.linspace(1,10,5)            # 定义段长 和arange相似,但是第三个参数指定的是
                                    # 多少段,也就是多少个数,
print(g)

h = np.linspace(1,10,6).reshape((2,3))   # 可以更改形状
print(h)

result:

[ 1.    3.25  5.5   7.75 10.  ]

[[ 1.   2.8  4.6]
 [ 6.4  8.2 10. ]]

3. The basic operation
for the matrix also add, subtract, multiply, divide operations.
Subtraction between the matrix and the normal operation of the same will not be repeated here. Directly on the code.

Addition, subtraction, multiplication with a single number

a = np.array([10,20,30,40])
b = np.arange(4)
print(a,b)
c = a-b                     # array 加法
d  = b**2                # 单个数乘法
print(c)
print(d)

result:

[10 20 30 40] [0 1 2 3]

[10 19 28 37]

[0 1 4 9]

Matrix multiplication

Represented by matrix multiplication .dot

a = np.array([[1,1],
              [0,1]])
b = b.reshape((2,2))
print(a)
print(b)
c= a*b      # 逐个元素相乘
c_dot = np.dot(a,b)   # 矩阵运算
c_dot_2 = a.dot(b)    # 同上
print(c)
print(c_dot)

result;

[[1 1]
 [0 1]]
 
[[0 1]
 [2 3]]
 
[[0 1]
 [0 3]]
 
[[2 4]
 [2 3]]

numpy also comes sin, cos, tan, etc. functions

e = 10*np.sin(a)            # np自带sin,cos,tan函数
print(e)

result:

[-5.44021111  9.12945251 -9.88031624  7.4511316 ]

axis、sum、min、max

When the axis = 0, column operations performed, when the axis = 1, row-operation.
Here Insert Picture Description

f = np.random.random((2,4))
print(f)
print(np.sum(f,axis=0))      # 当axis = 0时,进行列操作
                            # 当axis = 1时,进行行操作
print(np.min(f,axis=1))
print(np.max(f))

result:

[[0.59017978 0.81785528 0.1870801  0.32297439]
 [0.88120557 0.15484577 0.45264645 0.54394487]]
 
[1.47138535 0.97270106 0.63972654 0.86691925]

[0.1870801  0.15484577]

0.8812055728408469

Take down a string of codes is described below:

Attributes Explanation
np.argmin (A) The minimum value of the index
np.argmax (A) The maximum value of the index
np.mean(A) Average (also written as A.mean ())
npaverage(A) average value
np.median(A) Median
np.cumsum(A) Cumulative
np.diff(A) By difference
np.nonzero(A) The number of non-zero, the number of output rows and columns
np.sort(A) Progressive sorting
np.transpose(A) Transpose
A.T Transpose
np.clip(A,5,9) Filtering, all numbers greater than the number of all 9 becomes 0 becomes less than 5 5
np.mean(A,axis=0) Each column averaging

Code details:

import numpy as np

A = np.arange(2,14).reshape((3,4))

print(np.argmin(A))       # 最小值的索引
print(A)
print(np.argmax(A))        # 最大值索引
print(np.mean(A))          # 平均值
print(A.mean())

print(np.average(A))   # 平均值

print(np.median(A))  #中位数
print(np.cumsum(A))   # 累加

print(np.diff(A))  # 逐差
print(np.nonzero(A))  # 非零的数 输出行数和列数

print(np.sort(A))    # 逐行排序
print(np.transpose(A))    # 转置
print(A.T)            # 转置
print((A.T).dot(A))
print(np.clip(A,5,9))    #所有大于9的数变成9所有小于5的数变成5
print(np.mean(A,axis=0))

result:

0

[[ 2  3  4  5]
 [ 6  7  8  9]
 [10 11 12 13]]
 
11

7.5

7.5

7.5

7.5

[ 2  5  9 14 20 27 35 44 54 65 77 90]

[[1 1 1]
 [1 1 1]
 [1 1 1]]
 
(array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], dtype=int64), array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], dtype=int64))

[[ 2  3  4  5]
 [ 6  7  8  9]
 [10 11 12 13]]
 
[[ 2  6 10]
 [ 3  7 11]
 [ 4  8 12]
 [ 5  9 13]]
 
[[ 2  6 10]
 [ 3  7 11]
 [ 4  8 12]
 [ 5  9 13]]
 
[[140 158 176 194]
 [158 179 200 221]
 [176 200 224 248]
 [194 221 248 275]]
 
[[5 5 5 5]
 [6 7 8 9]
 [9 9 9 9]]
 
[6. 7. 8. 9.]

4. The index
array index starts from 0
microtome indexed form
Flatten () method of dimension reduction, so that all the data are arranged in a list.
A.flat also dimensionality reduction, but it must be in order to output all values with an iterator
Code;

import numpy as np

A = np.arange(3,15).reshape((3,4))
print(A)
print(A[2][1])              # 索引 从0开始
print(A[2,1])
print(A[:,1])
print(A[1,1:3])        # 类似于切片

for row in A:           # 迭代每一行
    print(row)

for column in A.T:          # 迭代每一列
    print(column)

print(A.flatten())         # 降维一行
for item in A.flat:
    print(item)

result;

[[ 3  4  5  6]
 [ 7  8  9 10]
 [11 12 13 14]]
 
12

12

[ 4  8 12]
[8 9]

[3 4 5 6]
[ 7  8  9 10]
[11 12 13 14]

[ 3  7 11]
[ 4  8 12]
[ 5  9 13]
[ 6 10 14]

[ 3  4  5  6  7  8  9 10 11 12 13 14]

3
4
5
6
7
8
9
10
11
12
13
14

The combined 6.array
There are three main methods vertically stacked, horizontal stacking, CONCATENATE

Vertical addition

import numpy as np

A = np.array([1,1,1])
B = np.array([2,2,2])
C =np.vstack((A,B))
print(np.vstack((A,B)))      # vertical stack  垂直叠加
print(A.shape,C.shape)

result;

[[1 1 1]
 [2 2 2]]
 
(3,) (2, 3)

Horizontal stacking

D = np.hstack((A,B))  # horizontal stack    水平叠加
print(D)
print(A.shape,D.shape)

result:

[1 1 1 2 2 2]
(3,) (6,)

np.newaxis add a dimension
np.concatenate (_, axis =) for rows or columns into a combined control 1 represents a vertical axis are added, the addition level represents
the code:

A = np.array([1,1,1])[:,np.newaxis]   # 给列方向加一个维度  变成(3,1)
B = np.array([2,2,2])[:,np.newaxis]
print(np.hstack((A,B)))
C = np.concatenate((A,B,B,A),axis=1)    #横向合并 和hstack和vstack相似
print(C)

result:

[[1 2]
 [1 2]
 [1 2]]
 
[[1 2 2 1]
 [1 2 2 1]
 [1 2 2 1]]

7.array split
applications split diced, axis = 1, the block is divided into vertical, axis = 0, the level is divided into blocks.
array_split () can not be used when this aliquot
vsplit (): vertical split
hsplit (): a horizontal split
application look at the code;

import numpy as np

A = np.arange(12).reshape((3,4))
print(A)

print(np.split(A,2,axis=1))    # 将A垂直分割成两块
print(np.split(A,3,axis=0))    # 将A水平分割成两块
print(np.split(A,[1,3],axis=1)) # 分成1 2 1   中间列表[1,3] 可以解释为索引小于1为第一块,1到
                                # 3之间为第二块   大于3为第三块
print(np.split(A,[1,2,3],axis=1))    # 分成 1 1 1 1
print(np.array_split(A,3,axis=1))  # 不等分
print(np.vsplit(A,3))    # 垂直分割
print(np.hsplit(A,2))    # 水平分割

result;

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
 
[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11]])]
       
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]

[array([[0],
       [4],
       [8]]), array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]]), array([[ 3],
       [ 7],
       [11]])]
       
[array([[0],
       [4],
       [8]]), array([[1],
       [5],
       [9]]), array([[ 2],
       [ 6],
       [10]]), array([[ 3],
       [ 7],
       [11]])]
       
[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2],
       [ 6],
       [10]]), array([[ 3],
       [ 7],
       [11]])]
       
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]

[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11]])]

8.numpy copy of
the application copy of.
Since the establishment of an array or a matrix, a = np.arange (4), so that b = a, c = a, d = b at this time change a, b, c, d to any one of the other three will change, which is because, in memory only a np.arange (4), a, b , c, d is the index of the physical content after a change, that change the physical content, then the index points to other content will change.
If the other three do not want to change, you have to use the copy () This method will re-open the memory storing physical content.

import numpy as np

a = np.arange(4)
b = a
c = a
d = b
a[0] = 11
print('a',a)                # 浅度copy
print('b',b)
print('c',c)
print('d',d)
d[1:3] = [22,33]
print('a',a)
print('b',b)
print('c',c)
print('d',d)

b= a.copy()
a[3] =44
print('a',a)
print('b',b)

result;

a [11  1  2  3]
b [11  1  2  3]
c [11  1  2  3]
d [11  1  2  3]
#更改d的内容后:
a [11 22 33  3]
b [11 22 33  3]
c [11 22 33  3]
d [11 22 33  3]
#copy方法的应用,更改a的值后a,b的对比
a [11 22 33 44]
b [11 22 33  3]

(To be continued, he went on to add in the future after learning)

Guess you like

Origin blog.csdn.net/Prince_IT/article/details/91356621