Python data analysis and application of Numpy numerical calculation basics

Article directory

Numpy numerical calculation basics

A foundational module for data science computing. While completing scientific computing tasks, it can also be used as an efficient multi-dimensional data container for storing and processing large matrices. Numpy's data container can save any type of data, so it can quickly integrate various data. Numpy itself does not have many advanced data analysis tools.

learning target

  • Master how to create multi-dimensional arrays and generate random numbers with Numpy
  • Master the indexing and transformation of arrays
  • Master the basic usage of array matrix operations and general functions in Numpy
  • Master Numpy's methods of reading and writing files and commonly used statistical analysis functions

2.1 Array object ndarray

2.1.1 Create array object

2-1Create an array and view array properties
import numpy as np	#导入numpy库
arr1=np.array([1,2,3,4])	#创建一个一维数组
print('创建的数据为:',arr1)	#打印
创建的数据为: [1 2 3 4]
arr2=np.array([[1,2,3,4],[4,5,6,7],[7,8,9,10]])	##创建一个三维数组`
print('创建的三维数组为:\n',arr2)	#打印
创建的三维数组为:
 [[ 1  2  3  4]
 [ 4  5  6  7]
 [ 7  8  9 10]]
print('数组维度为:',arr2.shape)	#查看数组结构
数组维度为: (3, 4)
print('数组类型为:',arr2.dtype)	#查看数组类型
数组类型为: int32
print('数组元素个数为:',arr2.size)	#查看数组元素个数`
数组元素个数为: 12
print('数组每个元素大小为:',arr2.itemsize)	#查看数组每个元素的大小
数组每个元素大小为: 4
2-2 Reset the shape attribute of the array
arr2.shape=4,3	#重新设置数组维度`
print('重新设置的数组2的维度为:',arr2.shape)`
重新设置的数组2的维度为: (4, 3)`
print('重新设置维度的数组2为:\n',arr2)`
重新设置维度的数组2为:`
 [[ 1  2  3]
 [ 4  4  5]
 [ 6  7  7]
 [ 8  9 10]]

The above method is to first generate a python sequence and then use the array function to convert it into an array form, which is less efficient. Therefore, numpy provides many functions specifically for creating arrays.

2-3 Use the arange function to create an array

The starting value, final value, and step size are one-dimensional arrays, excluding the final value.

print('使用arange函数创建的数组为:\n',np.arange(0,1,0.1)) #使用arange函数创建0开始,1.0为终值,步长为0.1的数组	
使用arange函数创建的数组为:
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
2-4 Use the linspace function to create an array

The linspace function creates a one-dimensional array by specifying the starting value, final value and number of elements. The final value is included by default (different from arange)

print('使用linspace函数生成的数组为:\n',np.linspace(0,1,10))
使用linspace函数生成的数组为:
 [0.         0.11111111 0.22222222 0.33333333 0.44444444 0.55555556 0.66666667 0.77777778 0.88888889 1.        ]
2-5 Use the logspace function to create a geometric series

The logspace function is similar to the linspace function and creates a geometric sequence.

Create 20 geometric sequences from 10 0 (1) to 10 (10)

print('使用logspace函数创建的等比数列为:\n',np.logspace(0,10,20))
使用logspace函数创建的等比数列为:
 [1.00000000e+00 3.35981829e+00 1.12883789e+01 3.79269019e+01
 1.27427499e+02 4.28133240e+02 1.43844989e+03 4.83293024e+03
 1.62377674e+04 5.45559478e+04 1.83298071e+05 6.15848211e+05
 2.06913808e+06 6.95192796e+06 2.33572147e+07 7.84759970e+07 2.63665090e+08 8.85866790e+08 2.97635144e+09 1.00000000e+10]
2-6 Use the zeros function to create an array

Provides other special functions to create arrays, zeros, eye, diag, ones, etc.

The zeros function creates an array with all elements equal to 0

print('zeros函数创建的数组:\n',np.zeros((2,3)))
zeros函数创建的数组:
 [[0. 0. 0.] `
2-7 Use the eye function to create an array

The eye function creates an array with a diagonal of 1

print('eye函数创建的数组:\n',np.eye((3)))
eye函数创建的数组:
 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
2-8 Use the diag function to create an array

The diag function creates a diagonal-like array, with elements other than the diagonal being 0, and the diagonal elements being 0 or other numbers.

``print('Array created by diag function:\n',np.diag([1,2,3])) Array created by diag function: [[1 0 0] [0 2 0]
[0 0 3] ]`

2-9 Use the ones function to create an array

The ones function creates an array with all elements being 1

print('ones函数创建的数组:\n',np.ones((3)))
ones函数创建的数组:
 [1. 1. 1.]
2-10 Array data type conversion
print('转换结果为:\n',np.float64(32))	#int转换为float

转换结果为:
 32.0
print('转换结果为:\n',np.int8(42.0))	#float转换为int

转换结果为:
 42
print('转换结果为:\n',np.bool(42))	#int转换为布尔类型

转换结果为:
 True
 
print('转换结果为:\n',np.bool(0))	#int到bool类型

转换结果为:
 False

print('转换结果为:\n',np.float(True))	#bool到浮点型

转换结果为:
 1.0

print('转换结果为:\n',np.float(False))	#布尔到浮点型

转换结果为:
 0.0
2-11Create data types
df=np.dtype([("name",np.str_,40),("numitems",np.int64),("price",np.float64)])

print('数据类型为:\n',df)
数据类型为:
 [('name', '<U40'), ('numitems', '<i8'), ('price', '<f8')]
2-12 View data types
print('数据类型为:\n',df["name"])

数据类型为:
 <U40

print('数据类型为:\n',np.dtype(df["name"]))

数据类型为:
 <U40

When using the array function to create an array, the default data type of the array is floating point. Custom arrays can specify the data type

Custom array data

itemz=np.array([("tomatoes",42,4.14),("cabbages",13,1.72)],dtype=df)
print('自定义数据为:\n',itemz)

自定义数据为:
 [('tomatoes', 42, 4.14) ('cabbages', 13, 1.72)]

2.1.2 Generate random numbers

random is the most commonly used function to generate random numbers

print('生成的随机数组为:',np.random.random(100))	#每次生成的随机数都不一样

生成的随机数组为: [0.5414394  0.5012236  0.35249272 0.09769069 0.6475065  0.98641875
 0.64135529 0.08061222 0.04190536 0.03458307 0.08118907 0.68696491
 0.51004343 0.6858908  0.54504495 0.98814038 0.26325152 0.74208912
 0.54847215 0.12902914 0.44575298 0.06392824 0.08550842 0.06104936
 0.7926837  0.0144069  0.07766267 0.58615123 0.61704458 0.27513275
 0.25431812 0.92537037 0.15578226 0.68445613 0.02767364 0.38113537
 0.79595552 0.8260522  0.59981855 0.32827585 0.1126209  0.24992717
 0.91755226 0.06445743 0.10480144 0.84633844 0.7064718  0.16507553
 0.34488413 0.95952993 0.64346169 0.76231375 0.6661867  0.02587888
 0.26290033 0.28978876 0.68573666 0.3530325  0.26461015 0.64860455
 0.09969484 0.71772394 0.0178291  0.22189977 0.08611602 0.91256162
 0.37283443 0.54140164 0.69328537 0.63926342 0.98635428 0.86592274
 0.4146884  0.25501787 0.69481642 0.97776931 0.81314084 0.93928548
 0.06571086 0.93979774 0.57665148 0.26755796 0.78038513 0.18855067
 0.55590344 0.48810975 0.89531296 0.48303248 0.99821839 0.55081464
 0.28083176 0.29653623 0.13610769 0.71791088 0.37012591 0.72331635
 0.84702313 0.66458812 0.21930531 0.90331974]

The rand function is used to generate random numbers that obey a uniform distribution.

print('生成的随机数组为:',np.random.rand(10,5))

生成的随机数组为: [[0.01932417 0.01791003 0.74598223 0.76213752 0.75621956]
 [0.10245317 0.64091723 0.44050907 0.72125074 0.797107  ]
 [0.79630621 0.78402876 0.89969261 0.13664477 0.73312912]
 [0.02421392 0.59043566 0.597735   0.47476056 0.13479233]
 [0.40949046 0.94931334 0.24626724 0.15688518 0.4430787 ]
 [0.16666454 0.0717138  0.42882409 0.92195781 0.19430092]
 [0.39851859 0.71871671 0.87534222 0.84967326 0.15873748]
 [0.37974825 0.34834934 0.67042749 0.56788288 0.71355081]

The randh function is used to generate random numbers following a normal distribution.

print('生成的随机数组为:',np.random.randn(10,5))

生成的随机数组为: [[ 1.27352466 -0.0659775   0.01888002  1.31867737 -1.6837147 ]
 [-0.00567767  1.54918115  0.28218841  2.0030673  -0.80086495]
 [-0.19758532 -0.39607603 -0.99615034 -0.53079879  0.8369686 ]
 [-0.62874687  0.61947075 -0.53059219  0.86770825  2.16602977]
 [-1.34455605 -0.6352837   0.5382481   0.88364061  1.29529511]
 [ 0.22003359  2.23242998  0.58226151  2.13286719  0.97495864]
 [ 0.89660402 -1.09040434 -0.12308345 -0.4312826  -1.01142497]
 [-2.72122353 -1.05665528  1.28831854 -0.96534334 -1.18869332]
 [-0.17032955 -0.53721905 -0.28488351  1.36280418  0.28442919]
 [-1.18284567 -0.18156955 -1.10135001 -0.95745263 -1.33624823]]

The randiant function can generate random numbers with a given upper and lower limit range. The format is as follows:
numpy.random.randiant(low.high=None,size=None,dtype='1')

print('生成的随机数组为:',np.random.randint(2,10,size=[2,5]))	#返回值为最小值不低于2,不大于5的2行5列的数组

生成的随机数组为: [[5 5 5 6 6]
 [2 2 5 7 4]]

2.1.3 Accessing arrays by index

Numpy is known for improving efficiency with arrays, all thanks to the ease of use of indexing. The main thing to learn is the indexing method of one-dimensional arrays and multi-dimensional arrays.

  1. The indexing of one-dimensional arrays
    is consistent with the indexing method of lists in Python
2-18 Using index to access one-dimensional array
arr=np.arange(10)	#创建一个数组
print('数组为:\n',arr)	#打印数组

数组为:
 [0 1 2 3 4 5 6 7 8 9]
 
print('索引结果为:\n',arr[5])	#打印数组索引为5的元素
索引结果为:
 5
 
print('索引结果为:\n',arr[3:5])	#打印数组索引从3到5的元素
索引结果为:
 [3 4]
 
print('索引结果为:\n',arr[:5])	#打印索引为5及其之前的所有元素
索引结果为:
 [0 1 2 3 4]
 
print('索引结果为:\n',arr[-1])	#打印倒数第一个元素
索引结果为:
 9
 
arr[2:4]=100,101	#重新定义数组
print('索引结果为:\n',arr)	#打印新建的数组
索引结果为:
 [  0   1 100 101   4   5   6   7   8   9]
 
print('索引结果为:\n',arr[1:-1:2])	#打印从索引1到倒数第一个元素,以2为步长的元素集合
索引结果为:
 [  1 101   5   7]
 
print('索引结果为:\n',arr[5:1:-2])	#打印索引5到1步长为-2的所有元素
索引结果为:
 [  5 101]
2-19 Access multidimensional arrays using indexes
arr=np.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]])		#创建2行5列数组
print('创建的二维数组为:\n',arr)		#打印数组
创建的二维数组为:
 [[ 1  2  3  4  5]
 [ 4  5  6  7  8]
 [ 7  8  9 10 11]]
 
print('索引结果为:\n',arr[0,3:5])	#打印索引为0的行的索引3到5列
索引结果为:
 [4 5]
 
print('索引结果为:\n',arr[1:,2:])	#打印索引为1行及其之后行的索引为2列之后的元素
索引结果为:
 [[ 6  7  8]
 [ 9 10 11]]
 
print('索引结果为:\n',arr[:,2])		#打印所有行的索引为2的列
索引结果为:
 [3 6 9]
2-20 Accessing multidimensional arrays using integer functions and boolean indexing
创建的二维数组为:
 [[ 1  2  3  4  5]
 [ 4  5  6  7  8]
 [ 7  8  9 10 11]]
 
print('索引结果为:\n',arr[[0,1,2],[1,2,3]])
#使用两个数组分别对应行和列的下标
索引结果为:
 [ 2  6 10]
 
print('索引结果为:\n',arr[1:,(0,2,3)])
#打印索引1及之后行的0,2,3索引列
索引结果为:
 [[ 4  6  7]
 [ 7  9 10]]
 
mask=np.array([1,0,1],dtype=np.bool)
#mask是一个布尔数组,
print('',mask)
 [ True False  True]
 
print('索引结果为:',arr[mask,2])	#索引第1,3行中第2列元素
索引结果为: [3 9]

2.1.4 Transform the shape of the array

2-21Change the shape of the array

When operating on an array, the dimensions of the array are often changed. In Numpy, the reshape function is commonly used to change the "shape" of an array, that is, to change the dimensions of the array.
Its parameter is a tuple of positive integers specifying the size of the array in each dimension.
The reshape function changes the shape of the original data without changing the value of the original data. If the specified dimension does not match the number of elements of the original array, an exception will be thrown.

arr=np.arange(12)
print(arr)
[ 0  1  2  3  4  5  6  7  8  9 10 11]

print('新的一维数组为:',arr.reshape(3,4))	#改变数组的维度
新的一维数组为: [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

print('新的数组维度为:',arr.reshape(3,4).ndim)
新的数组维度为: 2
2-22 Use the ravel function to flatten an array
arr=np.arange(12).reshape(3,4)
print('创建的二维数组为:',arr)
创建的二维数组为: [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
print('创建的二维数组展平后为:',arr.ravel())
创建的二维数组展平后为: [ 0  1  2  3  4  5  6  7  8  9 10 11]
2-23flatten function flattens the array
print('创建的二维数组展平后为:',arr.flatten())	#横向展平数组
创建的二维数组展平后为: [ 0  1  2  3  4  5  6  7  8  9 10 11]

print('创建的二维数组展平为:',arr.flatten('F'))	#纵向展平数组
创建的二维数组展平后为: [ 0  4  8  1  5  9  2  6 10  3  7 11]
2-24 Use the hstack function to combine arrays horizontally

Requirements for combining arrays

arr1=np.arange(12).reshape(3,4)
print("数组1为:",arr1)
数组1为: [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
arr2=arr1*3
print('数组2为:',arr2)
数组2为: [[ 0  3  6  9]
 [12 15 18 21]
 [24 27 30 33]]
print('横向组合为:',np.hstack((arr1,arr2)))
横向组合为: [[ 0  1  2  3  0  3  6  9]
 [ 4  5  6  7 12 15 18 21]
 [ 8  9 10 11 24 27 30 33]]
2-25 Use the vstack function to combine arrays vertically
print('纵向组合为:',np.vstack((arr1,arr2)))
纵向组合为: [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [ 0  3  6  9]
 [12 15 18 21]
 [24 27 30 33]]
2-26 Use the concatenate function to combine functions
print('横向组合为:',np.concatenate((arr1,arr2),axis=1))
横向组合为: [[ 0  1  2  3  0  3  6  9]
 [ 4  5  6  7 12 15 18 21]
 [ 8  9 10 11 24 27 30 33]]
 
print('纵向组合为:',np.concatenate((arr1,arr2),axis=0))
纵向组合为: [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [ 0  3  6  9]
 [12 15 18 21]
 [24 27 30 33]]

2-27 Use the hsplit function to achieve horizontal splitting of an array

arr=np.arange(16).reshape(4,4)
print(arr)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
 
print('横向分割为:\n',np.hsplit(arr1,2))
横向分割为:
 [array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11]])]

2-28 Use vsplit function to achieve vertical splitting of arrays

print('纵向分割为:\n',np.vsplit(arr,2))
纵向分割为:
 [array([[0, 1, 2, 3],
       [4, 5, 6, 7]]), array([[ 8,  9, 10, 11],
       [12, 13, 14, 15]])]

2-29 Use the split function to split an array

print('横向分割为:\n',np.split(arr,2,axis=1))
横向分割为:
 [array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11],
       [14, 15]])]

print('纵向分割为:\n',np.split(arr,2,axis=0))
纵向分割为:
 [array([[0, 1, 2, 3],
       [4, 5, 6, 7]]), array([[ 8,  9, 10, 11],
       [12, 13, 14, 15]])]

Numpy matrices and general functions

Create Numpy matrix

2-30 Use mat function and matrix function to create matrices
import numpy as np
matr1=np.mat("1 2 3;4 5 6;7 8 9")

print('创建的矩阵为:\n',matr1)
创建的矩阵为:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
matr2=np.matrix([[1,2,3],[4,5,6],[7,8,9]])
print('创建的矩阵为:\n',matr2)
创建的矩阵为:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
2-31 Use the bmat function to create a matrix
arr1=np.eye(3)
print(arr1)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
 
arr2=arr1*3
print(arr2)
[[3. 0. 0.]
 [0. 3. 0.]
 [0. 0. 3.]]
 
print('创建的矩阵为:\n',np.bmat("arr1 arr2; arr1 arr2"))	
#将小的矩阵创建为大的矩阵,即将小矩阵组合成为大矩阵。在numpy中,使用bmat分块矩阵函数实现
创建的矩阵为:
 [[1. 0. 0. 3. 0. 0.]
 [0. 1. 0. 0. 3. 0.]
 [0. 0. 1. 0. 0. 3.]
 [1. 0. 0. 3. 0. 0.]
 [0. 1. 0. 0. 3. 0.]
 [0. 0. 1. 0. 0. 3.]]
2-32 Matrix operations

In numpy, matrix calculations are performed for each element in the entire matrix. Compared with using a for loop, it will be faster in operation speed.

matr1=np.mat("1 2 3;4 5 6;7 8 9")	#创建矩阵
print(matr1)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
 
matr2=matr1*3	#矩阵与数字相乘
print(matr2)
[[ 3  6  9]
 [12 15 18]
 [21 24 27]]

print("矩阵相加结果为:\n",matr1+matr2)	#矩阵相加
矩阵相加结果为:
 [[ 4  8 12]
 [16 20 24]
 [28 32 36]]
 
print("矩阵相减结果为:\n",matr1-matr2)	#矩阵相减
矩阵相减结果为:
 [[ -2  -4  -6]
 [ -8 -10 -12]
 [-14 -16 -18]]
 
print("矩阵相乘结果为:\n",matr1*matr2)	#矩阵相乘
矩阵相乘结果为:
 [[ 90 108 126]
 [198 243 288]
 [306 378 450]]
 
2-33 Properties of matrices
print("矩阵转置结果为:\n",matr1.T)	#矩阵的转置
矩阵转置结果为:
 [[1 4 7]
 [2 5 8]
 [3 6 9]]
 
print("矩阵共轭转置结果为:\n",matr1.H)	#矩阵的共轭矩阵
矩阵共轭转置结果为:
 [[1 4 7]
 [2 5 8]
 [3 6 9]]
 
print("矩阵的逆矩阵结果为:\n",matr1.I)	#矩阵的逆矩阵
矩阵的逆矩阵结果为:
 [[ 3.15251974e+15 -6.30503948e+15  3.15251974e+15]
 [-6.30503948e+15  1.26100790e+16 -6.30503948e+15]
 [ 3.15251974e+15 -6.30503948e+15  3.15251974e+15]]
 
print("矩阵的二维数组结果为:\n",matr1.A)	#矩阵的二维展示
矩阵的二维数组结果为:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

Master the ufunc function

The ufunc function stands for universal function, which is a function that can operate on all elements in an array. The ufunc function operates on arrays and uses numpy arrays as output, so there is no need to operate on every element of the array. When performing repeated operations on an array, using the ufunc function is much more efficient than using the functions in the math library.

  1. Commonly used ufunc function operations
    include four arithmetic operations, comparison operations and logical operations.
    The ufunc function supports all four arithmetic operations and retains the customary operators, which are used in the same way as numerical operations. However, it should be noted that the object of the operation is an array.
    The four arithmetic operations between arrays means that the elements in each array undergo four arithmetic operations respectively, so the shapes of the two arrays for which the four arithmetic operations are performed must be the same.
Four arithmetic operations on 2-34 arrays
x=np.array([1,2,3])
y=np.array([4,5,6])

print('相加:\n',x+y)
相加:
 [5 7 9]
print('相减:\n',x-y)
相减:
 [-3 -3 -3]
print('相乘:\n',x*y)
相乘:
 [ 4 10 18]
print('相除:\n',x/y)
相除:
 [0.25 0.4  0.5 ]
print('幂运算:\n',x**y)
幂运算:
 [  1  32 729]
2-35 Array comparison operations

Full comparison operations are available in numpy.
The return value is a Boolean value, each element of which is the comparison result of the corresponding element of the array.

x=np.array([1,2,3])
y=np.array([4,5,6])

print('数组比较结果:\n',x<y)
数组比较结果:
 [ True  True  True]
 
print('数组比较结果:\n',x>y)
数组比较结果:
 [False False False]
 
print('数组比较结果:\n',x==y)
数组比较结果:
 [False False False]
 
print('数组比较结果:\n',x>=y)
数组比较结果:
 [False False False]
 
print('数组比较结果:\n',x<=y)
数组比较结果:
 [ True  True  True]
 
print('数组比较结果:\n',x!=y)
数组比较结果:
 [ True  True  True]
2-36 Logical operations on arrays

In numpy's logical operations, numpy.all means and, which means and, and numpy.any means or, which means or.

print('数组逻辑计算结果为:\n',np.all(x==y))
数组逻辑计算结果为:
 False
 
print('数组逻辑计算结果为:\n',np.any(x==y))
数组逻辑计算结果为:
 False
  1. Broadcasting mechanism of ufunc function
    Broadcasting refers to the way arithmetic operations are performed between arrays of different shapes. This is different from ufunc.

Principles of broadcast mechanism:

  • Let all input arrays be aligned with the array with the longest shape, and the missing part in the shape is made up by adding 1 in front.
  • The shape of the output array is the maximum value on each axis of the shape of the input array.
  • If an axis of the input array has the same length as the corresponding axis of the output array or its length is 1, then this array can be used for calculation, otherwise an error occurs
  • When the length of an axis of the input array is 1, the first group on this axis is used when operating along this axis.
2-37 Broadcasting mechanism of one-dimensional array
arr1=np.array([[0,0,0],[1,1,1],[2,2,2],[3,3,3]])
print(arr1)
[[0 0 0]
 [1 1 1]
 [2 2 2]
 [3 3 3]]
 
print("数组1的shape为:\n",arr1.shape)
数组1的shape为:
 (4, 3)
 
arr2=np.array([1,2,3])
print('数组2为:\n',arr2)
数组2为:
 [1 2 3]
 
print('数组2的shape为:\n',arr2.shape)
数组2的shape为:
 (3,)

print('数组相加的结果为:\n',arr1+arr2)
数组相加的结果为:
 [[1 2 3]
 [2 3 4]
 [3 4 5]
 [4 5 6]]
2-38 Broadcasting mechanism of two-dimensional array
arr1=np.array([[0,0,0],[1,1,1],[2,2,2],[3,3,3]])
print('数组1为:\n',arr1)
数组1为:
 [[0 0 0]
 [1 1 1]
 [2 2 2]
 [3 3 3]]
print('数组1的维度为:\n',arr1.shape)
数组1的维度为:
 (4, 3)
 
arr2=np.array([1,2,3,4]).reshape((4,1))
print('数组2为:\n',arr2)
数组2为:
 [[1]
 [2]
 [3]
 [4]]
print('数组2的维度为:\n',arr2.shape)
数组2的维度为:
 (4, 1)
 
print('数组相加的结果为:\n',arr1+arr2)
数组相加的结果为:
 [[1 1 1]
 [3 3 3]
 [5 5 5]
 [7 7 7]]

Using Numpy for statistics

Array operations are simpler and faster, often several times faster than the equivalent Python method, especially when dealing with array statistical calculations and analysis.

Read/write files

Numpy's file reading and writing mainly includes binary file reading and writing and data reading and writing in the form of file lists.

The basis for data processing using Numpy when reading and writing files. Secondly, it also provides several functions that can save the results to binary or text files. A number of methods are also provided for reading data from files and converting them into arrays.

The save function saves data in binary format, and the load function reads data from a binary file.
The syntax format of the save function:
np.save(file,arr,allow_pickle=True,fix_imports=True)

2-39 Binary data storage
import numpy as np
arr=np.arange(100).reshape(10,10)
np.save("../save_arr",arr)
print('保存的数组为:\n',arr)
保存的数组为:
 [[ 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 27 28 29]
 [30 31 32 33 34 35 36 37 38 39]
 [40 41 42 43 44 45 46 47 48 49]
 [50 51 52 53 54 55 56 57 58 59]
 [60 61 62 63 64 65 66 67 68 69]
 [70 71 72 73 74 75 76 77 78 79]
 [80 81 82 83 84 85 86 87 88 89]
2-40+ array storage
arr1=np.array([[1,2,3],[4,5,6]])
arr2=np.arange(0,1.0,0.1)
np.savez('../savez_arr',arr1,arr2)
print('保存的数组1为:\n',arr1)
保存的数组1为:
 [[1 2 3]
 [4 5 6]]
print('保存的数组2为:\n',arr2)
保存的数组2为:
 [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
2-41 Binary file reading
loaded_data=np.load("../save_arr.npy")
print('读取的数组为:\n',loaded_data)
读取的数组为:
 [[ 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 27 28 29]
 [30 31 32 33 34 35 36 37 38 39]
 [40 41 42 43 44 45 46 47 48 49]
 [50 51 52 53 54 55 56 57 58 59]
 [60 61 62 63 64 65 66 67 68 69]
 [70 71 72 73 74 75 76 77 78 79]
 [80 81 82 83 84 85 86 87 88 89]
 [90 91 92 93 94 95 96 97 98 99]]
 
print('读取的数组1为:\n',loaded_data1['arr_0'])
读取的数组1为:
 [[1 2 3]
 [4 5 6]]
 
print('读取的数组2为:\n',loaded_data1['arr_1'])
读取的数组2为:
 [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

It should be noted that the extension can be omitted when storing data, but cannot be omitted when reading.

2-42 File storage and reading

In actual data analysis tasks, more data in text format are used. Such as txt or csv format, so the savetxt function, loadtxt function, and genformtxt function are often used to perform the task of reading text format data.

The savetxtx function can write an array to a text file separated by a certain delimiter. The syntax format is as follows:
np.savetxt(fname,X,fmt='%.18e',delimiter=' ',newline='\n' , header='', footer=' ', comments='# ')
file name, array array, data delimiter
The loadtxt function performs the opposite operation, that is, loading the file into a two-dimensional array.

np.savetxt('../arr.txt', arr , fmt="%d", delimiter=',')
loaded_data=np.loadtxt('../arr.txt',delimiter=",")
print('读取的数组为:',loaded_data)
读取的数组为: [[ 0.  0.  1.  1.  2.  2.]
 [ 3.  3.  4.  4.  5.  5.]
 [ 6.  6.  7.  7.  8.  8.]
 [ 9.  9. 10. 10. 11. 11.]]
2-43 Use the genfromtxt function to read an array

The genfromtxt function is similar to the loadtxt function, but it works with structured arrays and missing data.

There are usually three parameters, the file name parameter fname, the split character parameter delimiter, and whether it contains the column title parameter names.

loaded_data=np.genfromtxt("../arr.txt",delimiter=",")
print('读取的数组为:\n',loaded_data)
读取的数组为:
 [[ 0.  0.  1.  1.  2.  2.]
 [ 3.  3.  4.  4.  5.  5.]
 [ 6.  6.  7.  7.  8.  8.]
 [ 9.  9. 10. 10. 11. 11.]]

Use functions to perform simple statistical analysis

  1. The main ways of sorting
    numpy sorting can be summarized as direct sorting and introduction sorting.
    Direct sorting refers to sorting values ​​directly; indirect sorting refers to sorting a data set based on one or more keys. The sort function is often used in direct sorting, and the argsort function and lexsort function are often used in indirect sorting.

The sort function is the most commonly used sorting method and has no return value. If the target function is a view, the original data will be modified. When using the sort function to sort, you can specify an axis parameter so that the sort function can sort the data set along the specified axis.

2-44 Use the sort function to sort
np.random.seed(42)
arr=np.random.randint(1,10,size=10)
print('创建的数组为:\n',arr)
创建的数组为:
 [7 4 8 5 7 3 7 8 5 4]
 
arr.sort()
print('排序后数组为:\n',arr)
排序后数组为:
 [3 4 4 5 5 7 7 7 8 8]
 
arr=np.random.randint(1,10,size=(3,3))	
#生成3行3列的数组
print('创建的数组为:\n',arr)
创建的数组为:
 [[8 8 3]
 [6 5 2]
 [8 6 2]]
 
arr.sort(axis=1)	#按照横轴进行排序
print('排序后数组为:\n',arr)
排序后数组为:
 [[3 8 8]
 [2 5 6]
 [2 6 8]]
 
arr.sort(axis=0)	#按照纵轴进行排序
print('排序后数组为:\n',arr)
排序后数组为:
 [[2 5 6]
 [2 6 8]
 [3 8 8]]
2-45 Use the argsort function for sorting

Using the argsort function and the lexsort function, you can get an index array composed of integers when given one or more keys. The index value represents the position of the data in the new sequence.

arr=np.array([2,3,6,8,0,7])
print('创建的数组为:\n',arr)
创建的数组为:
 [2 3 6 8 0 7]
 
print('排序后的数组为:\n',arr.argsort())
#返回值为重新排序值的下标
排序后的数组为:
 [4 0 1 2 5 3]
2-46 Sort using the lexsort function

The lexsort function can perform indirect sorting on arrays that satisfy multiple keys at once.

a=np.array([3,2,6,4,5])
b=np.array([50,30,40,20,10])
c=np.array([400,300,600,100,200])
d=np.lexsort((a,b,c))
print('【排序后数组为:\n',list(zip(a[d],b[d],c[d])))
【排序后数组为:
 [(4, 20, 100), (5, 10, 200), (2, 30, 300), (3, 50, 400), (6, 40, 600)]
  1. Deduplication and duplicate data
    In statistical analysis work, dirty data will inevitably appear.
    Duplicate data is one of the cases of dirty data. It would be very inefficient to delete them one by one.
    In numpy, you can use the unique function to find the unique value in an array and return the sorted result.
2-47 Deduplication of data in array
names=np.array(['小明','小黄','小花','小明','小花','小兰','小白'])
print('创建的数组为:\n',names)
创建的数组为:
 ['小明' '小黄' '小花' '小明' '小花' '小兰' '小白']

print('去重后的数组为:\n',np.unique(names))
去重后的数组为:
 ['小兰' '小明' '小白' '小花' '小黄']
print('去重后的数组为:\n',sorted(set(names)))
去重后的数组为:
 ['小兰', '小明', '小白', '小花', '小黄']
 
ints=np.array([1,2,3,4,4,5,6,6,7,8,8,9,10])
print('创建的数组为:\n',ints)
创建的数组为:
 [ 1  2  3  4  4  5  6  6  7  8  8  9 10]
 print('去重后的数组为:\n',np.unique(ints))
去重后的数组为:
 [ 1  2  3  4  5  6  7  8  9 10]

In addition, repeating a data several times is also required in statistical analysis.

2-48 Use the tile function to implement data duplication

In numpy, the file function and repeat function are mainly used to implement data repetition.

The format of the tile function is as follows:
numpy.tile(A.reps)
A specifies the repeated array, and the parameter reps specifies the number of repetitions.

arr=np.arange(5)
print(arr)
[0 1 2 3 4]

print('重复后的数组为:\n',np.tile(arr,3))
重复后的数组为:
 [0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]
2-49 Use the repeat function to implement data repetition

The format of the repeat function is as follows:
numpy.repeat(a,repeats,axis=None)
a refers to the elements participating in the repetition, repeats refers to the number of repetitions, and axis refers to the axis along which the repetition is performed.

np.random.seed(42)
arr=np.random.randint(0,10,size=(3,3))
print(arr)
[[6 3 7]
 [4 6 9]
 [2 6 7]]
 
print('重复后的数组为:\n',arr.repeat(2,axis=0))
#沿着x轴进行重复
重复后的数组为:	
 [[6 3 7]
 [6 3 7]
 [4 6 9]
 [4 6 9]
 [2 6 7]
 [2 6 7]]
 
print('重复后的数组为:\n',arr.repeat(2,axis=1))
#沿着y轴进行重复
重复后的数组为:
 [[6 6 3 3 7 7]
 [4 4 6 6 9 9]
 [2 2 6 6 7 7]]

The main difference between the two functions is that the tile function performs repeated operations on the array, and the repeat function performs repeated operations on each element in the array.
3. Commonly used statistical functions
Common statistical functions include sum, mean, std, var, min, max, etc.
Almost all statistical functions need to pay attention to the concept of axis when calculating for two-dimensional arrays.
When the axis parameter is 0, it means the calculation is performed along the vertical axis; when it is 1, it means the calculation is performed along the horizontal axis. But by default, the function does not calculate along any axis, but calculates a total value.

2-50 Use of commonly used statistical functions
arr=np.arange(20).reshape(4,5)
print(arr)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
 
print('数组的和为:\n',np.sum(arr))
数组的和为:
 190

print('数组纵轴的和为:\n',arr.sum(axis=0))
数组纵轴的和为:
 [30 34 38 42 46]
 
print('数组横轴的和为:\n',arr.sum(axis=1))
数组横轴的和为:
 [10 35 60 85]
 
print('数组均值为:\n',np.mean(arr))
数组均值为:
 9.5
 
print('数组纵轴的均值为:\n',arr.mean(axis=0))
数组纵轴的均值为:
 [ 7.5  8.5  9.5 10.5 11.5]
 
print('数组横轴的均值为:\n',arr.mean(axis=1))
数组横轴的均值为:
 [ 2.  7. 12. 17.]
 
print('数组的标准差为:\n',np.std(arr))
数组的标准差为:
 5.766281297335398

print('数组的方差为:\n',np.var(arr))
数组的方差为:
 33.25
 
print('数组的最小值为:\n',np.min(arr))
数组的最小值为:
 0
 
print('数组的最大值为:\n',np.max(arr))
数组的最大值为:
 19
 
print('数组的最小值的索引为:\n',np.argmin(arr))
数组的最小值的索引为:
 0
 
print('数组的最大值的索引为:\n',np.argmax(arr))
数组的最大值的索引为:
 19

The calculations of the functions used above are all aggregate calculations, and the final results of the calculations are directly displayed.

2-51Usage of cumsum function and cumprod function

But in numpy, the cumsum and cumprod functions use non-aggregation calculations to produce an array composed of intermediate results.

arr=np.arange(2,10)
print(arr)
[2 3 4 5 6 7 8 9]

print('数组元素的累计和为:\n',np.cumsum(arr))
数组元素的累计和为:
 [ 2  5  9 14 20 27 35 44]
 
print('数组元素的累计积为:\n',np.cumprod(arr))
数组元素的累计积为:
 [     2      6     24    120    720   5040  40320 362880]

Practical training

Practical training 1 Create arrays and perform operations

1. Training points
(1) Master NumPy’s array creation and random number generation.
(2) Master the basic operation functions used for statistical analysis in NumPy.
2. Requirement Description
NumPy arrays are more efficient in numerical operations than the lists provided by Python, so it is necessary to flexibly master the creation of arrays and basic operations in NumPy.
3. Implementation ideas and steps
(1) Create an array with a value ranging from 0 to 1 and an interval of 0.01.

print('1.1的结果为:\n',np.arange(0,1,0.01))
1.1的结果为:
 [0.   0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1  0.11 0.12 0.13
 0.14 0.15 0.16 0.17 0.18 0.19 0.2  0.21 0.22 0.23 0.24 0.25 0.26 0.27
 0.28 0.29 0.3  0.31 0.32 0.33 0.34 0.35 0.36 0.37 0.38 0.39 0.4  0.41
 0.42 0.43 0.44 0.45 0.46 0.47 0.48 0.49 0.5  0.51 0.52 0.53 0.54 0.55
 0.56 0.57 0.58 0.59 0.6  0.61 0.62 0.63 0.64 0.65 0.66 0.67 0.68 0.69
 0.7  0.71 0.72 0.73 0.74 0.75 0.76 0.77 0.78 0.79 0.8  0.81 0.82 0.83
 0.84 0.85 0.86 0.87 0.88 0.89 0.9  0.91 0.92 0.93 0.94 0.95 0.96 0.97
 0.98 0.99]

(2) Create 100 random numbers obeying the normal distribution.

print('1.2的结果为:\n',np.random.randn(100))
1.2的结果为:
 [-0.88523035 -0.41218848 -0.4826188   0.16416482  0.23309524  0.11799461
  1.46237812  1.53871497 -2.43910582  0.60344123 -0.25104397 -0.16386712
 -1.47632969  1.48698096 -0.02445518  0.35555132  0.41701111  0.83246186
 -0.29339915 -0.02983857  0.09512578  0.66465434 -0.1402185  -0.0331934
 -0.74907652 -0.77838201  0.94884286  1.58085059 -0.36817094  0.37556463
 -1.19315823 -0.4090519  -0.44674147  1.52424163  0.3229998  -1.39341694
 -2.17833425 -1.04389641  0.17269371  0.32419877  0.74585954 -1.83658324
  0.56446424  0.02550067  0.47319325  0.6591906   2.34074633  1.07098519
  0.09641648  0.41910211 -0.95302779 -1.0478706  -1.87567677 -1.36678214
  0.63630511 -0.90672067  0.47604259  1.30366127  0.21158701  0.59704465
 -0.89633518 -0.11198782  1.46894129 -1.12389833  0.9500054   1.72651647
  0.45788508 -1.68428738  0.32684522 -0.08111895  0.46779475  0.73612235
 -0.77970188 -0.84389636 -0.15053386 -0.96555767  0.15048908 -0.11342125
  2.63352822 -1.02509089 -0.78204783  0.42394307  0.8727051   2.28722598
  1.6229205   0.82373308  0.29305925  0.89663038 -0.61032202 -0.3161659
 -1.48242425 -0.22884752  0.96264129 -0.20969244 -0.77404293 -0.35977815
  0.72408325 -0.25576464  0.8499212  -1.31132423]

(3) Perform four arithmetic operations on the two created arrays.

print('两个数组的和为:,\n',arr1+arr2)
两个数组的和为:,
 [-0.87030495 -0.49664322 -1.28995069  2.97366342 -1.0562658   0.96488432
 -0.60606062 -0.44378749  0.3813228  -1.36851692 -0.56273831 -0.03647281
 -0.72601702 -0.69248937  1.22672702  1.15498688 -0.28176602  0.08583491
  1.41701607 -1.23647888  0.53802266  2.1845712   2.18503476 -1.70991122
 -0.52262696  0.41865939 -1.06187695 -0.3982467   0.142709    1.69132156
  0.25459734  0.52693673  0.83242373  0.87348869  0.36809946 -0.84708706
  1.1496728   0.80148946 -0.7167523  -0.29230156  1.28751161  1.01548313
 -0.30029799  0.16006623  0.29653777  1.06700378  1.7089407   0.53564916
  1.64920765  1.36331697  0.70565013 -0.93348335 -0.50771086  1.27124064
 -1.17052958  0.66897849  1.56048561  0.72242086 -0.02139725 -0.25661436
  1.41615272  1.08170729  0.3345107   1.69529247  1.49399779  2.43859386
  1.22689407  0.50549957  0.53700907 -1.2445702   0.85065904  0.69428506
 -0.61007407  0.70471237  2.08316821  0.01545235 -0.19989463  1.87492822
  1.4142403   3.85109521 -0.51857016  1.53038724  1.13589091  0.88928128
  1.75051222  0.82027464 -1.07637621  0.02264247  2.24443345  2.0620289
  0.52688081  1.41359706  3.70393805  0.8988132   0.92841668  1.14059871
  1.56697571  0.62109882  1.58612936 -0.95422959]
  
print('两个数组的差为:,\n',arr1-arr2)
两个数组的差为:,
 [ 0.87030495  0.51664322  1.32995069 -2.91366342  1.1362658  -0.86488432
  0.72606062  0.58378749 -0.2213228   1.54851692  0.76273831  0.25647281
  0.96601702  0.95248937 -0.94672702 -0.85498688  0.60176602  0.25416509
 -1.05701607  1.61647888 -0.13802266 -1.7645712  -1.74503476  2.16991122
  1.00262696  0.08134061  1.58187695  0.9382467   0.417291   -1.11132156
  0.34540266  0.09306327 -0.19242373 -0.21348869  0.31190054  1.54708706
 -0.4296728  -0.06148946  1.4767523   1.07230156 -0.48751161 -0.19548313
  1.14029799  0.69993377  0.58346223 -0.16700378 -0.7889407   0.40435084
 -0.68920765 -0.38331697  0.29434987  1.95348335  1.54771086 -0.21124064
  2.25052958  0.43102151 -0.44048561  0.41757914  1.18139725  1.43661436
 -0.21615272  0.13829271  0.9054893  -0.43529247 -0.21399779 -1.13859386
  0.09310593  0.83450043  0.82299093  2.6245702   0.54934096  0.72571494
  2.05007407  0.75528763 -0.60316821  1.48454765  1.71989463 -0.33492822
  0.1457597  -2.27109521  2.11857016  0.08961276  0.50410909  0.77071872
 -0.07051222  0.87972536  2.79637621  1.71735753 -0.48443345 -0.2820289
  1.27311919  0.40640294 -1.86393805  0.9611868   0.95158332  0.75940129
  0.35302429  1.31890118  0.37387064  2.93422959]

print('两个数组的积为:,\n',arr1*arr2)
两个数组的积为:,
 [-0.         -0.00506643 -0.02619901  0.0883099  -0.04385063  0.04574422
 -0.03996364 -0.03596512  0.02410582 -0.13126652 -0.06627383 -0.01611201
 -0.10152204 -0.10692362  0.15214178  0.15074803 -0.07068256 -0.01430806
  0.22266289 -0.27103099  0.06760453  0.41465995  0.43230765 -0.44617958
 -0.18303047  0.04216485 -0.34368801 -0.18042661 -0.03844148  0.40638325
 -0.0136208   0.06725039  0.16397559  0.17935127  0.00955382 -0.41898047
  0.28428221  0.1596511  -0.41676587 -0.26609761  0.35500465  0.24824808
 -0.30252516 -0.11607152 -0.06312338  0.2776517   0.57451272  0.0308551
  0.56121967  0.42792531  0.10282507 -0.73617651 -0.53440965  0.39285754
 -0.92368597  0.06543817  0.56027194  0.08687989 -0.3488104  -0.49950247
  0.48969163  0.28774145 -0.17700337  0.67113426  0.54655858  1.16258601
  0.37415009 -0.11021529 -0.09723384 -1.33485343  0.10546133 -0.01115761
 -0.95765333 -0.01845997  0.99394448 -0.55091074 -0.72951992  0.85079473
  0.49470743  2.41826522 -1.05485613  0.58351367  0.25903054  0.04920347
  0.76483026 -0.02526655 -1.66528354 -0.73720105  1.20070143  1.04310572
 -0.33580727  0.45827333  2.561223   -0.02900372 -0.01088832  0.18106877
  0.58269668 -0.33843415  0.59400678 -1.9247873 ]
  
print('两个数组的商为:,\n',arr1/arr2)
两个数组的商为:,
 [-0.00000000e+00 -1.97377555e-02 -1.52677503e-02  1.01913826e-02
 -3.64875016e-02  5.46517180e-02 -9.00818907e-02 -1.36243099e-01
  2.65496005e-01 -6.17065176e-02 -1.50889119e-01 -7.50992641e-01
 -1.41841119e-01 -1.58056754e-01  1.28827200e-01  1.49255680e-01
 -3.62182675e-01 -2.01983993e+00  1.45511448e-01 -1.33195102e-01
  5.91676311e-01  1.06352205e-01  1.11957307e-01 -1.18562127e-01
 -3.14701697e-01  1.48227741e+00 -1.96690017e-01 -4.04042400e-01
 -2.03946357e+00  2.06947504e-01 -6.60754306e+00  1.42898810e+00
  6.24483176e-01  6.07188347e-01  1.20998752e+01 -2.92376395e-01
  4.55885017e-01  8.57494867e-01 -3.46477505e-01 -5.71594762e-01
  4.50698327e-01  6.77145207e-01 -5.83092004e-01 -1.59298335e+00
 -3.06700935e+00  7.29331031e-01  3.68312123e-01  7.15926927e+00
  4.10534434e-01  5.61079216e-01  2.43131376e+00 -3.53312007e-01
 -5.05978888e-01  7.15017465e-01 -3.15691706e-01  4.62268425e+00
  5.59728192e-01  3.73964555e+00 -9.64420779e-01 -6.96893450e-01
  7.35156525e-01  1.29317484e+00 -2.17171011e+00  5.91386890e-01
  7.49416462e-01  3.63413973e-01  1.16423867e+00 -4.07293758e+00
 -4.75554623e+00 -3.56668371e-01  4.64625278e+00 -4.51799375e+01
 -5.41323238e-01 -2.88678744e+01  5.50936207e-01 -1.02103655e+00
 -7.91753568e-01  6.96877849e-01  1.22981779e+00  2.58077565e-01
 -6.06717810e-01  1.12439526e+00  2.59583287e+00  1.40010463e+01
  9.22557636e-01 -2.85951143e+01 -4.44128571e-01 -1.02672127e+00
  6.44956338e-01  7.59366938e-01 -2.41209786e+00  1.80700021e+00
  3.30467124e-01 -2.98203103e+01 -8.11511741e+01  4.98429409e+00
  1.58161189e+00 -2.78015681e+00  1.61681657e+00 -5.09199121e-01]

(4) Perform simple statistical analysis on the created random array.

print('1.4的统计分析结果的数组和为:\n',np.sum(arr2))
1.4的统计分析结果的数组和为:
 6.7340096554519
 
print('1.4的统计分析结果的均值为:\n',np.mean(arr2))
1.4的统计分析结果的均值为:
 0.067340096554519
 
print('1.4的统计分析结果的标准差为:\n',np.std(arr2))
1.4的统计分析结果的标准差为:
 1.0449116390258357
 
print('1.4的统计分析结果的方差为:\n',np.var(arr2))
1.4的统计分析结果的方差为:
 1.0918403333716586
 
print('1.4的统计分析结果的最小值为:\n',np.min(arr2))
1.4的统计分析结果的最小值为:
 -1.9442295937495997
 
print('1.4的统计分析结果的最小值为:\n',np.max(arr2))
1.4的统计分析结果的最小值为:
 3.06109521437826

Practical training 2 Create a chess board

1. Training points
(1) Master the matrix creation method. (2) Master the method of array indexing.
2. Requirement description
Create a chess board and fill in an 8x8 matrix. The chess board is a square, consisting of 64 small squares with 8 horizontal and vertical squares and staggered colors of one dark and one light. The dark squares are black squares and the light colored squares are white squares. The chess pieces move in these squares, such as As shown in Figure 2-3.
Insert image description here
3. Implementation ideas and steps
(1) Create an 8x8 matrix.
(2) Set the elements in rows 1, 3, 5, and 7 and columns 2, 4, and 6 to 1.

cheese=np.zeros((8,8),dtype=int)
print(cheese)
[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]]

cheese[1::2,::2]=1
print(cheese)
[[0 0 0 0 0 0 0 0]
 [1 0 1 0 1 0 1 0]
 [0 0 0 0 0 0 0 0]
 [1 0 1 0 1 0 1 0]
 [0 0 0 0 0 0 0 0]
 [1 0 1 0 1 0 1 0]
 [0 0 0 0 0 0 0 0]
 [1 0 1 0 1 0 1 0]]
 
cheese[::2,1::2]=1
print(cheese)
[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

Guess you like

Origin blog.csdn.net/m0_49265034/article/details/125160453