Introduction to the

In NumPy, multidimensional arrays have some very useful functions built in, in addition to basic arithmetic operations, that can speed up our scientific calculations.

Simple function

Let’s look at some of the more common operands. Before we use them, we construct an array:

arr = np.arange(10)
Copy the code
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Copy the code

Evaluate the root of an element in an array:

np.sqrt(arr)
Copy the code
Array ([0, 1, 1.4142, 1.7321, 2., 2.2361, 2.4495, 2.6458, 2.8284, 3.])Copy the code

Exponential function with natural constant base E:

np.exp(arr)
Copy the code
Array ([1., 2.7183, 7.3891, 20.0855, 54.5982, 148.4132, 403.4288, 1096.6332, 2980.958, 8103.0839])Copy the code

Take the maximum value of both arrays to form a new array:

x = np.random.randn(8)
y = np.random.randn(8)
x,y
Copy the code
(array ([2.3594, 0.1995, 1.542, 0.9707, 1.307, 0.2863, 0.378, 0.7539]), array ([0.3313, 1.3497, 0.0699, 0.2467, 0.0119, 1.0048, 1.3272, 0.9193]))Copy the code
np.maximum(x, y)
Copy the code
Array ([0.3313, 1.3497, 0.0699, 0.2467, -0.0119, 1.0048, 1.3272, -0.7539])Copy the code

The decimal and integer parts of a floating-point number set:

arr = np.random.randn(7) * 5
Copy the code
Array ([7.7455, 0.1109, 3.7918, 3.3026, 4.3129, 0.0502, 0.25])Copy the code
remainder, whole_part = np.modf(arr)
Copy the code
(array ([0.7455, 0.1109, 0.7918, 0.3026, 0.3129, 0.0502, 0.25]), array ([- 7. 0. 3), and (3), 4, 0, and 0.]))Copy the code

Vectorized array operations

If you want to perform an operation between arrays, the common method is to loop through it, but this is inefficient. So Numpy provides a way to manipulate data between arrays.

The np. meshGrid function is used to quickly generate a grid point coordinate matrix.

Let’s look at some coordinate point code:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([[0, 1, 2], [0, 1, 2]])
y = np.array([[0, 0, 0], [1, 1, 1]])


plt.plot(x, y,
         color='green',
         marker='.',
         linestyle='')
plt.grid(True)
plt.show()
Copy the code

The X above is a two-dimensional array representing the X-axis positions of coordinate points.

Y is also a two-dimensional array that represents the Y-axis position of a coordinate point.

Take a look at the drawing:

So this is the combination of the six coordinates using the X and Y matrices.

The above two-dimensional array of X and Y was entered manually, which is definitely not desirable if the coordinates have a large number of points.

The result is the np.meshgrid function. This function can take two one-dimensional arrays and generate a two-dimensional X and Y matrix.

The above example can be rewritten as:

X = np. Array ([0]) y = np. Array ([0, 1]) xs and ys = np, meshgrid (x, y) xs and ys (array ([[0, 1, 2], [0, 1, 2]]), array ([[0, 0, 0], [1, 1, 1]])Copy the code

You can see that the xs and ys generated are the same as the manual input.

SQRT (x2+y2) SQRT (x^2+y^2) SQRT (x2+y2) SQRT (x2+y2) SQRT (x2+y2)

np.sqrt(xs ** 2 + ys ** 2)
Copy the code

Results:

Array ([[0, 1, 2], [1., 1.41421356, 2.23606798]])Copy the code

Because xs and ys are themselves 2 by 3 matrices, it’s also going to be 2 by 3 matrices.

Conditional logical expression

We can use conditional logical expressions when constructing arrays:

Xarr = np. Array ([1.1, 1.2, 1.3, 1.4, 1.5]) yarr = np, array ([2.1, 2.2, 2.3, 2.4, 2.5]) cond. = np array ([True, False, True, True, False])Copy the code

result = [(x if c else y)
          for x, y, c in zip(xarr, yarr, cond)]
result
Copy the code
[1.1, 2.2, 1.3, 1.4, 2.5]
Copy the code

To make things simpler, we can use the WHERE statement:

result = np.where(cond, xarr, yarr)
result
Copy the code
Array ([1.1, 2.2, 1.3, 1.4, 2.5])Copy the code

We can also change the value of the array based on where conditions:

Arr = Np.random. Randn (4, 4) ARR array([[0.7953, 0.1181, -0.7485, 0.585], [0.1527, -1.5657, -0.5625, -0.0327], [0.929, 0.4826, 0.0363, 1.0954], [0.9809, 0.5895, 1.5817, 0.5287]])Copy the code

Above we built a 4 by 4 array.

If the value is greater than 0, change the value to 2; if it is less than 0, change the value to -2:

np.where(arr > 0, 2, -2)
array([[ 2,  2, -2,  2],
       [ 2, -2, -2, -2],
       [-2, -2, -2,  2],
       [ 2, -2,  2, -2]])
Copy the code

Statistical methods

Numpy provides mean, sum and other statistical methods:

arr = np.random.randn(5, 4)
arr
arr.mean()
np.mean(arr)
arr.sum()
Copy the code

You can also count by dimension:

arr.mean(axis=1)
arr.sum(axis=0)
Copy the code

Cumsum:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7])
arr.cumsum()
Copy the code
array([ 0,  1,  3,  6, 10, 15, 21, 28])
Copy the code

Cumprod is used to calculate the multiplier:

arr = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
arr
arr.cumsum(axis=0)
Copy the code
array([[ 0,  1,  2],
       [ 3,  5,  7],
       [ 9, 12, 15]])
Copy the code
arr.cumprod(axis=1)
Copy the code
array([[  0,   0,   0],
       [  3,  12,  60],
       [  6,  42, 336]])
Copy the code

Boolean array

Any tests if there is one or more True in the array, while all checks if all values in the array are True:

bools = np.array([False, False, True, False])
bools.any()
True
Copy the code
bools.all()
False
Copy the code

The sorting

You can use sort to sort an array, as well as by a particular axis:

arr = np.random.randn(6)
arr.sort()
Copy the code
Array ([2.5579, 1.2943, 0.2972, 0.1516, 0.0765, 0.1608])Copy the code
arr = np.random.randn(5, 3)
arr
arr.sort(1)
arr
Copy the code
Array ([[0.8852, 0.4936, 0.1875], [0.3507, 0.1154, 0.0447], [1.1512, 0.8978, 0.8909], [2.6123, 0.8671, 1.1413]. [0.437, 0.3475, 0.3836]])Copy the code

Sort (1) refers to sorting by the second axis.

file

It is easy to write arrays to and read from files:

arr = np.arange(10)
np.save('some_array', arr)
Copy the code

Npy = some_array.npy = some_array.npy = some_array.npy = some_array.npy

np.load('some_array.npy')
Copy the code

It is also possible to store multiple arrays uncompressed:

np.savez('array_archive.npz', a=arr, b=arr)
Copy the code

Read:

arch = np.load('array_archive.npz')
arch['b']
Copy the code

If you want to compress, you can do this:

np.savez_compressed('arrays_compressed.npz', a=arr, b=arr)
Copy the code

Linear algebra

If we use ordinary arithmetic to perform matrix operations, just simple arithmetic operations on the corresponding elements of the array. If we want to multiply matrices, we can use dot.

I have a 2 by 3 matrix dot a 3 by 2 matrix, and I end up with a 2 by 2 matrix.

x = np.array([[1., 2., 3.], [4., 5., 6.]])
y = np.array([[6., 23.], [-1, 7], [8, 9]])
x
y
x.dot(y)
Copy the code
array([[ 28.,  64.],
       [ 67., 181.]])
Copy the code

Or you could write:

np.dot(x, y)
Copy the code
array([[ 28.,  64.],
       [ 67., 181.]])
Copy the code

You can also use the @ symbol:

x @ y
Copy the code
array([[ 28.,  64.],
       [ 67., 181.]])
Copy the code

Let’s take a look at the operations:

Product operation:

The operator describe
dot(a, b[, out]) Matrix is the dot product
linalg.multi_dot(arrays, *[, out]) Multiple matrix dot products
vdot(a, b) The vector dot product
inner(a, b) The inner product of two arrays
outer(a, b[, out]) The cross product of two vectors
Matmul (x1, x2, /[, out, casting, order,… ) Product of the corresponding bits of two matrices
tensordot(a, b[, axes]) Computes the tensor dot product along a specified axis
Einsum (subscripts, *operands[, out, dtype,… ) EinsteinPeace agreement
einsum_path(subscripts, *operands[, optimize]) Evaluate the lowest cost shrink order for einsum expressions by considering the creation of intermediate arrays.
linalg.matrix_power(a, n) Exponentiation of matrices
kron(a, b) Kronecker product of matrices

Decomposition operation:

The operator describe
linalg.cholesky(a) Choleskydecomposition
linalg.qr(a[, mode]) Compute the QR factorization of the matrix
Linalg. SVD (a [full_matrices, compute_uv,… ) Singular value decomposition

Eigenvalues and eigenvectors:

operation describe
linalg.eig(a) Compute the eigenvalues and the right eigenvectors of the square matrix.
linalg.eigh(a[, UPLO]) Returns the eigenvalues and eigenvectors of the complex Hermitian (conjugate symmetric) or real symmetric matrix.
linalg.eigvals(a) Compute the eigenvalues of a general matrix.
linalg.eigvalsh(a[, UPLO]) Compute the eigenvalues of the complex Hermitian (conjugate symmetric) or real symmetric matrix.

Basic value:

operation describe
linalg.norm(x[, ord, axis, keepdims]) Matrix or vector norm
linalg.cond(x[, p]) Compute the condition number of a matrix.
linalg.det(a) Matrix determinant
linalg.matrix_rank(M[, tol, hermitian]) Returns the matrix rank of the array using the SVD method
linalg.slogdet(a) Evaluates the sign and (natural) logarithm of the array determinant.
trace(a[, offset, axis1, axis2, dtype, out]) Returns the sum along the diagonals of an array.

Solution and inversion:

operation describe
linalg.solve(a, b) Solve linear matrix equations or linear scalar equations.
linalg.tensorsolve(a, b[, axes]) Solve the tensor equation ‘a x = b’ for x.
linalg.lstsq(a, b[, rcond]) Return the least squares solution to the linear matrix equation
linalg.inv(a) Compute the inverse of the matrix.
linalg.pinv(a[, rcond, hermitian]) Compute the (Moore-Penrose) pseudo inverse of the matrix.
linalg.tensorinv(a[, ind]) Compute the inverse of an n-dimensional array.

The random number

Most of the time we need to generate random numbers. In NumPy the generation of random numbers is very simple:

samples = np.random.normal(size=(4, 4))
samples
Copy the code
Array ([[2.0016, 0.3718, 1.669, 0.4386], [0.5397, 0.477, 3.2489, 1.0212], [0.5771, 0.1241, 0.3026, 0.5238]. [0.0009, 1.3438, -0.7135, -0.8312]])Copy the code

We used normal above to get an array of normally distributed 4×4 samples.

Using NP. Random is much faster than using Python’s native random number generator.

Np. random can specify the seed for generating random numbers:

np.random.seed(1234)
Copy the code

The numpy.random data generator uses a global random seed. To avoid global states, you can create a separate random number generator using numpy.random.randomState:

rng = np.random.RandomState(1234)
rng.randn(10)
Copy the code

This article is available at www.flydean.com/10-python-n…

The most popular interpretation, the most profound dry goods, the most concise tutorial, many tips you didn’t know waiting for you to discover!

Welcome to pay attention to my public number: “procedures those things”, understand technology, more understand you!