Preface:
NumPy is an extended library of programs for the Python language that supports a large number ofHigh-dimensional arrays and matrix operationsNumPy also provides a large library of mathematical functions for array arithmetic. NumPy is also one of the essential tools for machine learning.
The main common operations are:
- Creating Arrays
- array operation
- math function
- Array slicing and indexing
- Array shape operations
- Array Sorting
- array statistics
matrix
- Python 3.6
- NumPy: 1.14.2
1、Guide package
import numpy as np
2, through the list to create an array array()
([1, 2, 3]) # One-dimensional arrays ([(1, 2, 3), (4, 5, 6)]) #two-dimensional array
3. 0/1 arrays zeros(), ones()
((3, 3)) #3 rows and 3 columns ((2, 3, 4))
4. Array of equal differences arange() reshape()
#1D isometry (5) #array([0, 1, 2, 3, 4]) # Two-dimensional isotropy (6).reshape(2, 3) in the end: array([[0, 1, 2], [3, 4, 5]])
5. unit matrix eye()
(3) in the end: array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
7. Equally spaced arrays
#1D (1, 10, num=6) #array([ 1. , 2.8, 4.6, 6.4, 8.2, 10. ])
8. Random arrays
(2, 3) array([[0.40360777, 0.74141574, 0.32018331], [0.15261484, 0.18692149, 0.19351765]])
9. Randomized integer arrays
(10, size=(2, 3)) # Values less than 10 array([[2, 1, 0], [2, 7, 5]])
10, based on the function to create an array
(lambda i, j: i + j, (3, 6)) array([[0., 1., 2., 3., 4., 5.], [1., 2., 3., 4., 5., 6.], [2., 3., 4., 5., 6., 7.]])
array operation
+-*/ Addition, subtraction, multiplication and division, corresponding to positional elements
# Matrix multiplication (A, B) # Matrix multiplication can be accomplished directly using * if the two-dimensional array is accurately defined as a matrix using (A) * (B)
Transfers.
Matrix inverse.
(A)
e^x
(a)
Square root.
(a)
Cubic.
(a, 3)
Skinning and indexing arrays
One-dimensional arrays.
a = ([1, 2, 3, 4, 5]) # One-dimensional array index a[0], a[-1] # One-dimensional array slicing a[0:2], a[:-1]
A two-dimensional array.
a = ([(1, 2, 3), (4, 5, 6), (7, 8, 9)]) # Index a[0], a[-1] ######## Slicing # Take the second column a[:, 1] # Take rows 2 and 3 a[1:3, :]
Array Shape
Shape (number of rows and columns)
Changing the number of rows and columns
(2, 3) # points to the new object, reshape does not change the original array. # resize changes the original array (2, 3)
flatten an array
()
Vertical assembly of arrays, stacked on top of each other
((a, b))
Horizontal collocated arrays, placed next to each other
((a, b))
Split the array:
array([[5, 0, 2], [4, 2, 4], [4, 7, 9]]) # Split the array along the horizontal axis (a, 3) [array([[5], [4], [4]]), array([[0], [2], [7]]), array([[2], [4], [9]])] # Split the array along the vertical axis (a, 3) [array([[5, 0, 2]]), array([[4, 2, 4]]), array([[4, 7, 9]])]
Array sorting:
# Generate example arrays a = (([1, 4, 3], [6, 2, 9], [4, 7, 2])) # #### Returns the maximum value of each column (a, axis=0) # #### returns the minimum value per line (a, axis=1) # #### Returns the index of the maximum value per column (a, axis=0) # #### Returns the minimum value index per line (a, axis=1)
Array statistics:
# Continue to use the a-array from above (a, axis=0) # #### Counting the arithmetic mean of the rows of an array (a, axis=1) # #### Weighted average of the columns of a statistical array (a, axis=0) # #### Count the variance of each row of the array (a, axis=1) # #### Standard deviation of the columns of the statistics array (a, axis=0)
Advancement:
# #### 51. Create a 5x5 two-dimensional array with a boundary value of 1 and the rest of the values 0 # In[60]: Z = ((5,5)) Z[1:-1,1:-1] = 0 Z # #### 52. Use the number 0 to enclose a 5x5 2D array of all 1s. # In[61]: Z = ((5,5)) Z = (Z, pad_width=1, mode='constant', constant_values=0) Z # #### 53. Create a 5x5 two-dimensional array and set the values 1, 2, 3, 4 to fall below their diagonals # In[62]: Z = (1+(4),k=-1) Z # #### 54. Create a 10x10 two-dimensional array with 1's and 0's spaced diagonally. # In[63]: Z = ((10,10),dtype=int) Z[1::2,::2] = 1 Z[::2,1::2] = 1 Z # #### 55. Create a one-dimensional array of 0-10 and invert all numbers between (1, 9] into negative numbers # In[64]: Z = (11) Z[(1 < Z) & (Z <= 9)] *= -1 Z # #### 56. Finding the same element in two one-dimensional arrays # In[65]: Z1 = (0,10,10) Z2 = (0,10,10) print("Z1:", Z1) print("Z2:", Z2) np.intersect1d(Z1,Z2) # #### 57. Use NumPy to print yesterday's, today's, and tomorrow's dates # In[66]: yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D') today = np.datetime64('today', 'D') tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D') print("yesterday: ", yesterday) print("today: ", today) print("tomorrow: ", tomorrow) # #### 58. Use five different methods to extract the integer portion of a random array. # In[67]: Z = (0,10,10) print("Original value: ", Z) print ("Method 1:", Z - Z%1) print ("Method 2:", (Z)) print ("Method 3:", (Z)-1) print ("Method 4:", (int)) print ("Method 5:", (Z)) # #### 59. Create a 5x5 matrix where each row has values ranging from 1 to 5 # In[68]: Z = ((5,5)) Z += (1,6) Z # #### 60. Create an equally spaced one-dimensional array of length 5 with values ranging from 0 to 1, but excluding 0 and 1. # In[69]: Z = (0,1,6,endpoint=False)[1:] Z # #### 61. create a random one-dimensional array of length 10 and sort it in ascending order # In[70]: Z = (10) () Z # #### 62. create a 3x3 two-dimensional array and sort the columns in ascending order # In[71]: Z = ([[7,4,3],[3,1,2],[4,2,6]]) print("Original array: \n", Z) (axis=0) Z # #### 63. Create a one-dimensional array of length 5 and replace the maximum value with 0. # In[72]: Z = (5) print("Original array:",Z) Z[()] = 0 Z # #### 64. Prints the minimum and maximum values for each NumPy scalar type. # In[73]: for dtype in [np.int8, np.int32, np.int64]: print("The minimum value of {}: ".format(dtype), (dtype).min) print("The maximum value of {}: ".format(dtype),(dtype).max) for dtype in [np.float32, np.float64]: print("The minimum value of {}: ".format(dtype),(dtype).min) print("The maximum value of {}: ".format(dtype),(dtype).max) # #### 65. Converting `float32` to integer # In[74]: Z = (10, dtype=np.float32) print(Z) Z = (np.int32, copy=False) Z # #### 66. Randomize a two-dimensional array in ascending order from top to bottom in column 3 # In[75]: Z = (0,10,(5,5)) print("Before sorting: \n",Z) Z[Z[:,2].argsort()] # #### 67. Find the nearest number to a given value (0.5) from a random one-dimensional array # In[76]: Z = (0,1,20) print("Random array: \n", Z) z = 0.5 m = [(Z - z).argmin()] m # #### 68. Swap the first two rows of a two-dimensional array sequentially # In[77]: A = (25).reshape(5,5) print(A) A[[0,1]] = A[[1,0]] print(A) # #### 69. Find the value that occurs most frequently in a random one-dimensional array # In[78]: Z = (0,10,50) print("Random one-dimensional array:", Z) (Z).argmax() # #### 70. Find the index of the location of the non-zero element in a given one-dimensional array # In[79]: Z = ([1,0,2,0,1,0,4,0]) Z # #### 71. For a given 5x5 two-dimensional array, randomly place p numbers of value 1 inside it # In[80]: p = 3 Z = ((5,5)) (Z, (range(5*5), p, replace=False),1) Z # #### 72. For a random 3x3 two-dimensional array, subtract the average of each row of the array # In[81]: X = (3, 3) print(X) Y = X - (axis=1, keepdims=True) Y # #### 73. Getting diagonal arrays as a result of dot product of 2D arrays # In[82]: A = (0,1,(3,3)) B = (0,1,(3,3)) print((A, B)) # Slower methods ((A, B)) # In[83]: # Faster way (A * , axis=1) # In[84]: # A faster way ("ij, ji->i", A, B) # #### 74. find the first p largest values in a random one-dimensional array # In[85]: Z = (1,100,100) print(Z) p = 5 Z[(Z)[-p:]] # #### 75. Calculate the 4th power of each element of a random one-dimensional array # In[86]: x = (2,5,5) print(x) (x,4) # #### 76. For each element of a two-dimensional random array, retain its 2 decimal places # In[87]: Z = ((5,5)) print(Z) np.set_printoptions(precision=2) Z # #### 77. Exporting NumPy arrays using scientific notation # In[88]: Z = ([5,5]) print(Z) Z/1e3 # #### 78. Use NumPy to find percentile (25%, 50%, 75%) # In[89]: a = (15) print(a) (a, q=[25, 50, 75]) # #### 79. Find the total number of missing values in the array and where they are located. # In[90]: # Generate 2-dimensional arrays with missing values Z = (10,10) Z[(10, size=5), (10, size=5)] = Z # In[91]: print("Total number of missing values: \n", (Z).sum()) print("Missing value index: \n", ((Z))) # #### 80. Remove rows containing missing values from the random array # In[92]: # Renewal of the 2-dimensional array with missing values in question 79 Z[((Z), axis=1) == 0] # #### 81. Counting the number of elements in a random array # In[93]: Z = (0,100,25).reshape(5,5) print(Z) (Z, return_counts=True) # of returned values, the 2nd array corresponds to the number of elements of the 1st array # #### 82. Converts elements of an array to text values according to a specified categorization # In[94]: # Designate categories as follows # 1 → Car # 2 → Bus # 3 → Train Z = (1,4,10) print(Z) label_map = {1: "Cars.", 2: "Bus.", 3: "Train."} [label_map[x] for x in Z] # #### 83. Collapsing multiple 1-dimensional arrays into a single Ndarray # In[95]: Z1 = (3) Z2 = (3,7) Z3 = (7,10) Z = ([Z1, Z2, Z3]) print(Z) (Z) # #### 84. prints the index of each element in ascending order in the array # In[96]: a = (100, size=10) print('Array: ', a) () # #### 85. Getting the maximum value of each row of a 2D random array # In[97]: Z = (1,100, [5,5]) print(Z) (Z, axis=1) # #### 86. get the minimum value of each row of a 2D random array (different from the method above) # In[98]: Z = (1,100, [5,5]) print(Z) np.apply_along_axis(, arr=Z, axis=1) # #### 87. Calculate the Euclidean distance between two arrays # In[99]: a = ([1, 2]) b = ([7, 8]) # Mathematical calculations print((((8-2), 2) + ((7-1), 2))) # NumPy calculations (b-a) # #### 88. Print the real and imaginary parts of a complex number # In[100]: a = ([1 + 2j, 3 + 4j, 5 + 6j]) print("The Real Ministry:", ) print("Virtual Ministry:", ) # #### 89. Solve the inverse matrix of the given matrix and verify that # In[101]: matrix = ([[1., 2.], [3., 4.]]) inverse_matrix = (matrix) # Verify that the dot product of the original and inverse matrices is a unit matrix assert ((matrix, inverse_matrix), (2)) inverse_matrix # #### 90. Normalization of data using the Z-Score normalization algorithm # Z-Score standardized formula: # $$Z = \frac{X-\mathrm{mean}(X)}{\mathrm{sd}(X)}$$ # In[102]: # Define the function according to the formula def zscore(x, axis = None): xmean = (axis=axis, keepdims=True) xstd = (x, axis=axis, keepdims=True) zscore = (x-xmean)/xstd return zscore # Generate randomized data Z = (10, size=(5,5)) print(Z) zscore(Z) # #### 91. Normalization of data using the Min-Max standardization algorithm # Min-Max standardized formula: # $$Y = \frac{Z-\min(Z)}{\max(Z)-\min(Z)}$$ # In[103]: # Define the function according to the formula def min_max(x, axis=None): min = (axis=axis, keepdims=True) max = (axis=axis, keepdims=True) result = (x-min)/(max-min) return result # Generate randomized data Z = (10, size=(5,5)) print(Z) min_max(Z) # #### 92. Normalization of data using L2 norms # L2 Paradigm formula: # $$L_2 = \sqrt{x_1^2 + x_2^2 + \ldots + x_i^2}$$ # In[104]: # Define the function according to the formula def l2_normalize(v, axis=-1, order=2): l2 = (v, ord = order, axis=axis, keepdims=True) l2[l2==0] = 1 return v/l2 # Generate randomized data Z = (10, size=(5,5)) print(Z) l2_normalize(Z) # #### 93. Calculating direct correlation coefficients of variables using NumPy # In[105]: Z = ([ [1, 2, 1, 9, 10, 3, 2, 6, 7], # Feature A [2, 1, 8, 3, 7, 5, 10, 7, 2], # Feature B [2, 1, 1, 8, 9, 4, 3, 5, 7]]) # Feature C (Z) # The correlation coefficient was varied from `[-1, 1]`, with values nearer to 1 representing a stronger positive correlation and -1 representing a stronger negative correlation. The result is shown below, the correlation coefficient between variable A and variable A directly is `1` because it is the same variable. The correlation coefficient between variable A and variable C is `0.97`, which indicates a strong correlation. # ``` # [A] [B] [C] # array([[ 1. , -0.06, 0.97] [A] # [-0.06, 1. , -0.01], [B] # [ 0.97, -0.01, 1. ]]) [C] # ``` # #### 94. Computing eigenvalues and eigenvectors of matrices using NumPy # In[106]: M = ([[1,2,3], [4,5,6], [7,8,9]]) w, v = (M) # w corresponds to eigenvalue, v corresponds to eigenvector w, v # We can back-calculate the `P'AP=M` formula to verify that we get the original matrix. # In[107]: v * (w) * (v) # #### 95. Calculating the difference between two neighboring elements of an Ndarray using NumPy # In[108]: Z = (1,10,10) print(Z) # Calculate the difference between two neighboring elements of Z print((Z, n=1)) # Repeat the calculation 2 times print((Z, n=2)) # Repeat the calculation 3 times print((Z, n=3)) # #### 96. Use NumPy to add neighboring elements of an Ndarray in order. # In[109]: Z = (1,10,10) print(Z) """ [first element, first element + second element, first element + second element + third element, ...] """ (Z) # #### 97. Using NumPy to join two arrays by columns # In[110]: M1 = ([1, 2, 3]) M2 = ([4, 5, 6]) np.c_[M1, M2] # #### 98. Using NumPy to join two arrays by rows # In[111]: M1 = ([1, 2, 3]) M2 = ([4, 5, 6]) np.r_[M1, M2] # #### 99. Printing multiplication tables with NumPy # In[112]: (lambda i, j: (i + 1) * (j + 1), (9, 9)) # #### 100. Using NumPy to convert lab building logos to Ndarray arrays # In[113]: from io import BytesIO from PIL import Image import PIL, requests # Download images via links URL = '/img/' response = (URL) # Read the content as an image I = (BytesIO()) # Convert images to Ndarray shiyanlou = (I) shiyanlou # In[114]: # Redraw the converted Ndarray into an image from matplotlib import pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') (shiyanlou) ()
To this point this article on python numpy summary of common operations is introduced to this article, more related python numpy content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!