Introduction to common usage of Python numpy Library

Time:2020-10-22

This article describes the common usage of Python numpy library. For your reference, the details are as follows:

1. Introduction

Numpy is a common Python science and Technology Library, through which you can quickly operate arrays, including shape operation, sorting, selection, input and output, discrete Fourier transform, basic linear algebra, basic statistical operation and random simulation. Many Python libraries and scientific computing software packages use numpy array as the operation object, or convert the incoming Python array into numpy array, so numpy is indispensable for data operation in Python.

The core of numpy is the ndarray object, which is encapsulated by Python’s n-dimensional array. However, numpy has higher execution efficiency than native Python by precompiling related array operations in C language. However, it still uses Python language to code, so it has concise code and efficient running speed. There are some differences between ndarry and array. It is worth noting that the elements in numpy array have the same type, and the fixed size is determined at the time of creation, which is different from that Python array objects can grow dynamically.

2. Array object

2.1. Properties

The form of numpy object is isomorphic multidimensional array. The dimension of array is called axis, and the number of elements in each dimension is called the length of axis. For example, the following is a 2 × 3 two-dimensional array arr, the length of the first axis is 3, and the length of the second axis is 2


arr = [[ 1., 0., 0.],
    [ 0., 1., 2.]]

The common attributes of arr array objects are as follows:

#Number of array axes
arr.ndim
#Array dimension and length, for example, the shape of 2 × 3 array is (2,3)
arr.shape
#The total number of array elements
arr.size
#The data type of the element in the array
arr.dtype
#The number of bytes occupied by elements in the array
arr.itemsize

2.2 create array

You can wrap an ordinary Python array with array () method, convert it into a numpy array, and specify the data type of elements by dtype =. An array can be a two-dimensional array of high dimensions, or it can be in the form of tuples.

If you need to fill an array of known size, you can use the function zeros() to fill all elements to 0, or ones() to fill elements to 1, empty() to fill elements as random numbers

The arange (a, B, c) function is used to generate an array element every C length from a to B. The linspace (a, B, c) function is used to generate C array elements from a to B

#Convert normal array to numpy array
a1 = np.array([2, 3, 4], dtype=float)
print(a1)                  
#Convert tuple array to 2D numpy array
a2 = np.array([(1, 2, 3), (3, 4, 5)])
print(a2)
#Fill a 3 × 3 array with 1
a3 = np.ones((3, 3))
print(a3)
#From 1 to 10, an element is generated every 2
a4 = np.arange(1, 10, 2)
print(a4)
#Four elements are generated between 1 and 12
a5 = np.linspace(1, 12, 4, dtype=int)
print(a5)
 
'''
Convert a normal array to a numpy object:
[2. 3. 4.]
Tuple array:
[[1 2 3]
 [3 4 5]]
Fill the array with 1:
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
From 1 to 10, an element is generated every 2:
[1 3 5 7 9]
Four elements are generated between 1 and 12:
[ 1 4 8 12]
'''

2.3 array operation

The arithmetic operator can be directly applied to the matrix, and the result is to apply the operation to each element. For example, the matrix A * B is the corresponding multiplication of each element, and the multiplication operation of the matrix uses the @ symbol

A = np.array([[1, 1],
       [0, 1]])
B = np.array([[2, 0],
       [3, 4]])
print(A * B)
print(A @ B)
 
'''
Matrix elements corresponding multiplication:
[[2 0]
 [0 4]]
Matrix multiplication:
[[5 4]
 [3 4]]
'''

Some functions in numpy apply to the entire array, such as sum, Max, min. If an axis is specified in these parameters, it is used to specify the axis.

There are also some functions applied to the specific elements of an array, such as finding sin, cos, exp, square root sqrt, and so on. These functions are called through functions

a = np.array([[0, 1, 2, 3],
       [4, 5, 6, 7],
       [8, 9, 10, 11]])
The maximum value of # A is obtained
Print (A. sum (axis = 0)) ා, the result is: [12 15 18 21]
print( np.sqrt (a) The square root of each element of the array

Arrays in numpy can be indexed, sliced, and iterated just like list in Python. The array a [x] represents the access to the elements of array a whose subscript is x, and the one-dimensional array a [x: y] represents accessing the elements from X to y in the array. If x is omitted, it means to start from the beginning, and Y means to the end. A [x: Y: a] represents that a value is taken every a element from X to y. if a is a negative number, it represents the value in reverse order.

a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Print (a [1:3]) ා outputs elements with subscripts 1 to 3: [1, 2]
Print (a [:: - 2]) in reverse order, select a value every two elements: [9 7 5 3 1]

If it is a multidimensional array, the indexes are separated by commas. You can use… To represent the omission of several dimensions. If omitted, it will be considered as the output of all the dimensions. For examplex[...,3]Equivalent tox[:,:,:,:,3]

You can iterate through the for loop, most of which are arrays, whose contents are subarrays of a lower dimension. If you want to traverse each child element, you can use the flat attribute.

a = np.array([[0, 1, 2, 3],
       [10, 11, 12, 13],
       [40, 41, 42, 43]])
#Output the first three of the first dimension (row) of a, and 1 ~ 3 of the subscript of the second dimension (column)
print(a[1:3, 0:3])
#Output all of the rows, columns with subscript 2
print(a[2, ...])
#Traversal array
for row in a:
  print(row)
#Traverse each child element
for item in a.flat:
  print(item)
 
'''
Columns 1-3 of the last two rows:
[[10 11 12]
 [40 41 42]]
All columns in the third row:
[40 41 42 43]
Traversal array:
[0 1 2 3]
[10 11 12 13]
[40 41 42 43]
Traverse each element:
0
1
2
......
41
42
43
'''

In addition to using specific numbers as indexes, you can also use numpy arrays as indexes. For example, using array I as the index of one-dimensional array a, output a [i]. When the array I is a multi-dimensional array, select the elements from a to fill in the corresponding position of the I array

a = np.arange(12) ** 2
print(a)
i = np.array([1, 3, 5])
print(a[i])
#Multidimensional array index J
j = np.array([[3, 4], [9, 7]])
print(a[j])
 
'''
[ 0  1  4  9 16 25 36 49 64 81 100 121]
1, 3, 5 elements of array a
[ 1 9 25]
Take the data of a and fill it in the corresponding position through the index J
[[ 9 16]
 [81 49]]
'''

If the selected dimension a represents a single array of elements

If the multidimensional array is indexed on multiple dimensions, multiple index arrays I, J are passed in and separated by commas

a = np.array(([[0, 1, 2, 3],
        [4, 5, 6, 7],
        [8, 9, 10, 11]]))
#Single element index of multidimensional array
i = np.array([0, 1])
print(a[i])
#Provide multi-dimensional index for multidimensional array, and provide I, j to get two elements [0,2] and [1,3] of A
j = np.array([2, 3])
print(a[i, j])
'''
Select rows 0 and 1 of multidimensional array A:
[[0 1 2 3]
 [4 5 6 7]]
The two elements of a are [0,2] and [1,3]
[2 7]
'''

2.4 changing dimensions

The reshape() method of an array can reconstruct the original array into an array of target dimensions. For example, a 2 × 6 array can be reconstructed into a 3 × 4 array,

Array will not modify the original array, but return the modified result array

It is worth noting that the array is reconstructed and printed from the rightmost dimension to the left. For example, for the 3 × 4 array B below, four rows are arranged first, and then the line is wrapped to arrange such three lines. If it is multidimensional, the output will continue in such a row and column. If the array dimension is – 1, the size of the dimension will be calculated automatically. For example, if the array contains 12 elements, and the second and third dimensions are 3 × 2, then the first dimension is 2

The travel() function expands an array into a one-dimensional array.

a=np.array([[1,2,3,4,5,6],
      [7,8,9,10,11,12]])
b=a.reshape(3,4)
print(b)
#Multidimensional array, automatic calculation
print(a.reshape(-1,3,2))
#Expand array
flatted = b.ravel()
print(flatted, end=' ')
'''
[[ 1 2 3 4]
 [ 5 6 7 8]
 [ 9 10 11 12]]
2 × 3 × 2 multidimensional array:
[[[ 1 2]
 [ 3 4]
 [ 5 6]]

 [[ 7 8]
 [ 9 10]
 [11 12]]]
Expand array:
[ 1 2 3 4 5 6 7 8 9 10 11 12] 
'''

Numpy’s hstack() function can merge multiple arrays horizontally, and vstack() can merge multiple arrays vertically

Instead, hsplit(), vsplit() can be split into a specified number of arrays

a=np.array([1,2,3])
b=np.array([4,5,6])
#Vertical merge
c=np.vstack((a,b))
print(c)
#Horizontal merge
print(np.hstack((a,b)))
#Split horizontally
print(np.hsplit(c,3))
'''
vertical stack 
[[1 2 3]
 [4 5 6]]
Horizontal consolidation
[1 2 3 4 5 6]
Horizontally split into three 1 × 2 cells:
[array([[1],
    [4]]), 
array([[2],
    [5]]), 
array([[3],
    [6]])]
'''

2.5. Copy array

When an array object is assigned to a new variable, does it open up a new storage space or just pass a reference? The answer is citation.

For example, executing the statement B = a only passes a reference to B, and the operation performed on B will directly affect a. The node ID of a and B is the same

a = np.array([1, 2, 3])
b = a
#Amendment B
b[0] = 0
print(a)
#Output the ID of a and B objects
print(id(a), id(b))
 
'''
Modifications B and a have also changed
[0 2 3]
View the IDs of both
2290013812656 2290013812656
'''

The view of the array is returned by slicing. Modifying the shape of the view will not affect the original array, but modifying the data on the view will also change the original array. After del A is executed, because C references a, a will still exist in memory and will not be deleted

c = a[:]
#Modify the shape of the view
c.shape = 3, 1
print(c, a)
#Modify the data of view C
c[0] = 1
print(a[0])
 
'''
Change the shape of view C, and a will not be affected
[[0]
 [2]
 [3]] [0 2 3]
If the data of C is modified, a will also change
1

The copy() method can generate a copy of the data, so the operation on the copy will not affect the original array at all

d= a.copy()
d[0]=5
#Modify the copy D and a of the array, and output a: [1, 2, 3]
print(a)

More interested readers about Python related content can view the special topics of this website: summary of Python mathematical operation skills, python data structure and algorithm tutorial, python function use skills summary, Python string operation skills summary, python introduction and advanced classic tutorial and python file and directory operation skills summary

I hope this article will be helpful to python programming.