Numpy. Working with arrays and matrices


Data library NumPy

NumPy — an open source library for the Python programming language, which implements a large number of operations for working with vectors, matrices and arrays. 

Mathematical algorithms implemented in interpreted languages ​​(eg Python) are often much slower than those implemented in compiled languages ​​(eg Fortran, C, Java). The NumPy library provides implementations of computational algorithms (in the form of functions and operators) optimized for working with multidimensional arrays. 
As a result, any algorithm that can be expressed as a sequence of operations on arrays (matrices) and implemented using NumPy is fast enough.

NumPy (Numeric Python) is a core math library for working with data. This library underlies other libraries for working with machine learning or data analysis tasks (for example, Pandas (working with tabular data), SciPy (optimization methods and scientific calculations), Matplotlib (plotting)).

 

Working with NumPy

In order to start working with the numpy library, you need to import it at the beginning of the program like any other library, import numpy or so (which is used more often) import numpy as np



NumPy Vectors

A vector (or array) in NumPy is an ordered set of homogeneous data.

An element of a vector can be accessed by its index, just as it is done in lists. Each element of the vector has its own specific place, which is set during creation.
All vector elements have the same data type (int, str, bool, etc.).

Creating a Vector
To create a vector, you need to use the numpy.array constructor (an iterable object).
Parentheses indicate any iterable object: tuple, list, range(), etc.
 
Example 
import numpy as np import numpy as np print(np.array((1,2,3,4,5))) # vector from tuple print(np.array([1,2,3,4,5])) # vector from list print(np.array(range(5))) # vector from generator

Working with vector elements

Working with vector elements is the same as with list elements, you can access elements by their index, and also make slices.

Example
1
2
3
4
5
6
7
import numpy as np V = np.array((1,2,3,4)) print(V[0]) # 1 print(V[-1]) # 4 print(V[1:-2]) # [2] print(V[::2]) # [1 3]

Selecting vector elements
To select vector elements, you can use a vector containing logical values ​​(expressions). The elements of the vector that will be True in the vector with boolean values ​​will be selected.
 

Example
import numpy as np V = np.array([1,-2,3,-4,5]) # select the first two elements of the vector print(V[np.array((True, True, False, False, False))]) # [ 1 -2] # select positive vector elements print(V[V > 0]) # [1 3 5] # select even vector elements print(V[V % 2 == 0]) # [-2 -4]

Ways to create arrays and matrices

Other useful ways to create arrays and matrices.

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
eleven
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
thirty
31
32
33
34
35
36
37
import numpy as np # One-dimensional array of zeros print(np.zero(5)) #[0. 0.0.0.0.] # Two-dimensional array of zeros print(np.zeros((2, 3))) # [[0. 0.0.] #[0. 0.0.]] # 3D array of units print(np.ones((2,3,4))) # [[[1. 1. 1. 1.] # [1. 1. 1. 1.] # [1. 1. 1. 1.]] # # [[1. 1. 1. 1.] # [1. 1. 1. 1.] # [1. 1. 1. 1.]]] # Array of zeros with type indication print(np.zeros(5, dtype=np.int)) # [0 0 0 0 0] # An array based on a list of lists print(np.array([[1,2.0],[0,0],(1,3.)])) # [[1. 2.] #[0. 0.] # [1. 3.]] # An array filled with elements of an arithmetic progression starting from 0 print(np.arange(10)) # [0 1 2 3 4 5 6 7 8 9] # Arithmetic progression with type indication print(np.arange(2, 10, dtype=np.float)) # [2. 3. 4. 5. 6. 7. 8. 9.] # Arithmetic progression with non-integer difference print(np.arange(2, 3, 0.1)) # [2. 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9] # Arithmetic progression with a given number of terms print(np.linspace(1., 4., 6)) # [1. 1.6 2.2 2.8 3.4 4. ]

Zero array elements
 
Function nonzero(V) 
The result is a tuple of arrays. Each such array corresponds to a separate axis of the original array and contains indices with non-zero elements in this array.
V - a NumPy array or array-like object.
Returns a Python tuple (tuple) - tuple with arrays of indexes of non-zero elements of the original array V.
 
Function count_nonzero(V) 
This function is based on the built-in  __bool__() method of Python objects that checks whether they are true. It follows that the  count_nonzero() function is actually able to work not only with numbers, but also with any objects that can be either true or false.
V - a NumPy array or array-like object.
The function returns the number of non-zero array elements along the specified axis.

Diagonal Arrays

The  diag(V, k=0) function allows you to extract a diagonal from an array, as well as build diagonal arrays from one-dimensional arrays.
V - An array-like object, two-dimensional or one-dimensional arrays, matrices, lists, or tuples, or any function or object with a method that returns a list or tuple.
k - index of the diagonal (optional).
The default is k = 0 which corresponds to the main diagonal. A positive k value moves the diagonal up, a negative value moves it down.

The function returns array NumPy (ndarray) - the specified array diagonal or a diagonal array from the specified one-dimensional array.

2D NumPy arrays

An element of a two-dimensional array is accessed by specifying the coordinates of the element, first the row number, then the column number. Coordinates are separated by commas. 
Any array can be converted to a two-dimensional array using the reshape(). function

Example
1
2
3
4
5
6
7
8
# The reshape() function changes the shape of an array without changing its data. x = np.arange(12).reshape(3, 4) print(x) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # To access an element, specify its coordinates separated by commas print(x[1, 2]) # 6