Some common operations and usage examples in numpy array


This article is to interpret some The commonly used numpy array operation is also to deepen your understanding of numpy. If you encounter more practical operations later, you will also synchronize to this article.

It has to be said that numpy has too many operations. A good way is to use it while learning, use it at any time and check it at any time. If you want to learn comprehensively or just want to query the function of a function, you can Visit the official website , the official website has a very comprehensive tutorial method, which is a great place to learn numpy.

1. Calculation of array and scalar

Operator operationmeaning
a+1Add 1 to all elements of a
a - 1All elements of a minus 1
a*3Multiply all elements of a by 3
1/a1 divided by all elements in a
1//a1 divided by all elements in a and rounded
a**0.5All elements of a are taken to the power of 0.5

Code example:

import numpy as np

a = np.array([1,2,3,4]).reshape(2,2)

print(a+2) #addition
'''
[[3 4]
 [5 6]]
'''
print(a*3) #multiplication
'''
[[ 3  6]
 [ 9 12]]
'''
print(1//a) # Division
'''
[[1 0]
 [0 0]]
'''
print(a**0.5) #Open root
'''
[[1.         1.41421356]
 [1.73205081 2.        ]]
'''

2. Mathematical calculation between two arrays

Operator operationmeaning
a+ba. B addition of corresponding elements
a-ba. B subtraction of corresponding elements
a*ba. B multiplies the corresponding elements
a/ba. B Division of corresponding elements
a//ba. B Division of corresponding elements
np.multiply(a, b)Dot multiplication, same as * sign
np.dot(a,b)inner product
np.matmulCross multiplication

Code example:

import numpy as np

a = np.array([1.2,2.6,-3.9,4.5]).reshape(2,2)
b = np.array([-2.6,3.6,2.8,13.6]).reshape(2,2)

print(a*b)
'''
[[ -3.12   9.36]
 [-10.92  61.2 ]]
'''
print(a//b)
'''
[[-1.  0.]
 [-2.  0.]]
'''

3. Mathematical operation of array unary function

functionmeaning
numpy.sqrt(array)Square root function
numpy.exp(array)Array of e^array[i]
numpy.abs/fabs(array)Calculate absolute value
numpy.square(array)Calculate the square of each element, equal to array**2
numpy.log/log10/log2(array)Calculate various logarithms of each element
numpy.sign(array)Calculate the sign of each element
numpy.isnan(array)NaN(not a number): not equal to any floating-point number
numpy.isinf(array)inf: larger than any floating point number
numpy.cos/cosh/sin/sinh/tan/tanh(array)trigonometric function
numpy.modf(array)The integer and decimal values in the array are separated and returned as two arrays
numpy.ceil(array)Round up, that is, take an integer larger than this number
numpy.floor(array)Round down, that is, take an integer smaller than this number
numpy.rint(array)rounding
numpy.trunc(array)Round to 0
numpy.cos(array)sine
numpy.sin(array)Cosine value
numpy.tan(array)Tangent value
numpy.sum(array)Sum
numpy.cumsum(array)Prefix Sum
numpy.mean(array)Average
numpy.std(array)Standard deviation
numpy.var(array)Find variance
numpy.min(array)Find the minimum value
numpy.max(array)Find the maximum value
numpy.argmin(array)Minimum index
numpy.argmax(array)Maximum index
numpy.media(array)The odd number takes the middle number, and the even number takes the average of the middle two numbers

Code example:

import numpy as np

a = np.array([1.2,2.6,-3.9,4.5]).reshape(2,2)

print(np.rint(a)) #rounding
'''
[[ 1.  3.]
 [-4.  4.]]
'''
print(np.abs(a)) #absolute value
'''
[[1.2 2.6]
 [3.9 4.5]]
'''
print(np.sin(a)) #sin value
'''
[[ 0.93203909  0.51550137]
 [ 0.68776616 -0.97753012]]
'''

print(np.sum(a)) #Summation 4.4

print(np.cumsum(a)) # Sum of current number and all previous numbers: [1.2 3.8 - 0.1 4.4]

print(np.argmin(a)) #Minimum index: 2

4. Mathematical operation of array binary function

functionmeaning
numpy.add(array1,array2)Element level addition
numpy.subtract(array1,array2)Element level subtraction
numpy.multiply(array1,array2)Element level multiplication
numpy.divide(array1,array2)Element level division array1/ array2
numpy.power(array1,array2)Element level index array1^ array2
numpy.maximum/minimum(array1,aray2)Element level maximum
numpy.fmax/fmin(array1,array2)Element level maximum, ignoring NaN
numpy.mod(array1,array2)Element level modulus
numpy.copysign(array1,array2)Copies the value symbol from the second array to the value in the first array
numpy.greater/greater_equal/less/less_equal/equal/not_equal (array1,array2)Element level comparison operation to generate boolean array
numpy.logical_end/logical_or/logic_xor(array1,array2)Element level truth logic operation

Code example:

import numpy as np

a = np.array([1.2,2.6,-3.9,4.5]).reshape(2,2)
b = np.array([-2.6,3.6,2.8,13.6]).reshape(2,2)

print(np.add(a,b)) #Addition of elements
'''
[[-1.4  6.2]
 [-1.1 18.1]]
'''
print(np.multiply(a,b)) #Element multiplication
'''
[[ -3.12   9.36]
 [-10.92  61.2 ]]
'''
print(np.maximum(a,b)) #a. Maximum element between B
'''
[[ 1.2  3.6]
 [ 2.8 13.6]]
'''
print(np.copysign(a,b))#Give the symbol of b to a
'''
[[-1.2  2.6]
 [ 3.9  4.5]]
'''

5. Common attributes of array

attributemeaning
dtypeThe data type of the array element
sizeNumber of array elements
ndimDimension of array
shapeDimension size of the array (in tuples)
TTranspose of array

Code example:

import numpy as np

a = np.array([1,2,3,4]).reshape(2,2)
print(a.dtype) #Type: int64
print(a.ndim)#Dimension: 2
print(a.shape)#Array size (2,2)
print(a.size)#Number of array elements: 4
print(a.T) #Transpose
'''
[[1 3]
 [2 4]]
'''

6. Common methods of array

Note that this is a method, not a function.

methodmeaning
reshapeModify shape without changing data
flatNot a method, it's an array element iterator
flattenReturns a copy of the array. Changes made to the copy will not affect the original array
ravelReturns an expanded array

Both flatten and t ravel can select the expansion order: Order: 'C' - by row, 'F' - by column, 'A' - original order, 'k' - the order of elements in memory.

import numpy as np

a = np.arange(4).reshape(2, 2)

for element in a.flat:
    print(element,end=", ") # 0, 1, 2, 3,
print('\n')
print (a.flatten()) #[0 1 2 3]

print (a.ravel(order = 'F')) #[0 2 1 3]

7. Random operation

numpy. The random module complements Python's built-in random and adds some functions for efficiently generating sample values of multiple probability distributions, such as normal distribution, Poisson distribution, etc. Since the application of using normal distribution has not been involved yet, this part only introduces some simple and practical random operations.

operationsignificance
random.rand()Generate data between [0,1] according to the given dimension
random.randn()According to a given dimension (a single number when no dimension is given), a random number conforming to the standard normal distribution is generated
random.normal()A random number that can define the normal distribution of mean and standard deviation
random.randint()Returns a random integer for a given dimension
random.random(),random.random_sample()Returns a random number between [0,1] of a given dimension
random.choice()Generates a random number from a given one-dimensional array

Code example:

import numpy as np

print(np.random.rand(3, 3)) #Random number of [0,1) in 3 * 3 dimension
print(np.random.random((3, 3))) #Random number of [0,1) in 3 * 3 dimension

print(np.random.randint(0, 2, size=(3, 3))) #Random integer of [0, 2] of 3 * 3 dimension

print(np.random.choice(['a', 'b', 'c'], p=[0.5, 0.3, 0.2])) #The sum of the probability values of p must be 1

8. Splicing array

import numpy as np

a = np.arange(4).reshape(2,2)
b = np.array([[5,6],[7,8]])

c = np.concatenate((a,b),axis=1)#Specify axis=1 splicing, and the default is axis=0 splicing
'''
[[0 1 5 6]
 [2 3 7 8]]
'''
c = np.concatenate((a,b))#Default axis=0
'''
[[0 1]
 [2 3]
 [5 6]
 [7 8]]
'''
c=np.hstack([a,b])#Transverse splicing
'''
[[0 1 5 6]
 [2 3 7 8]]
'''
c=np.vstack([a,b])#Longitudinal splicing
'''
[[0 1]
 [2 3]
 [5 6]
 [7 8]]
'''
b = np.array([[1,1],[1,1]])
c = np.append(b,a)#If axis is not specified, it will be expanded into one dimension by default. If axis is specified, it is as follows.
'''
[1 1 1 1 0 1 2 3 4 5 6 7]
'''

axis is set in append.

import numpy as np
a=[1,2,3]
b=[4,5]
c=[[6,7],[8,9]]
d=[[10,11],[12,13]]
print('In one-dimensional array a Add after values,The results are as follows:{0}'.format(np.append(a,b,axis=0)))
print('Along 2D array c Add new row direction values The results are as follows:{0}'.format(np.append(c,d,axis=0)))
print('Along 2D array c Column direction add values The results are as follows:{0}'.format(np.append(c,d,axis=1)))
#print('axis is used. If the shapes of arr and values are different, an error will be reported: '. format(np.append(a,c,axis=0)))

Output:

In one-dimensional array a Add after values,The results are as follows:[1 2 3 4 5]
Along 2D array c Add new row direction values The results are as follows:[[ 6  7]
 [ 8  9]
 [10 11]
 [12 13]]
Along 2D array c Column direction add values The results are as follows:[[ 6  7 10 11]
 [ 8  9 12 13]]

9. Split array

import numpy as np

a = np.arange(9)
print(np.split(a,[3,6]))#The original array is segmented according to the specified segmentation point
'''
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
'''

10. Insertion and deletion

import numpy as np

a = np.arange(8).reshape(2,4)

c = np.delete(a,[0,2],axis=1)#Delete on axis = 1, column 0,2
'''
[[1 3]
 [5 7]]
'''
c = np.insert(a,1,5,axis=1)#Insert the specified value on axis=1, and insert the number 5 in column 1
'''
[[0 5 1 2 3]
 [4 5 5 6 7]]
'''

11. Array extension

numpy provides tile function and repeat method, which can easily expand the array.

import numpy as np

a = np.array([1,2,3])
print(np.tile(a,[3,1])) #Copy into 3 rows and 1 column
'''
[[1 2 3]
 [1 2 3]
 [1 2 3]]
'''
print(a.repeat(3,axis=0))#Copy 3 lines above axis=0
'''
[1 1 1 2 2 2 3 3 3]
'''
a=np.array([[1,2,3]])
print(np.tile(a,[3,1])) #Copy into 3 rows and 1 column
'''
[[1 2 3]
 [1 2 3]
 [1 2 3]]
'''
print(a.repeat(3,axis=0))#Copy 3 lines above axis=0
'''
[[1 2 3]
 [1 2 3]
 [1 2 3]]
'''

Keywords: Python

Added by skattabrain on Mon, 03 Jan 2022 17:45:18 +0200