Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use functions in numpy

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you to introduce in detail "how to use the functions in numpy", the content is detailed, the steps are clear, the details are handled properly, I hope this article "how to use functions in numpy" can help you solve your doubts, the following follow the editor's ideas slowly in depth, let's learn new knowledge.

Brief introduction

In NumPy, in addition to the basic arithmetic operations, multi-dimensional arrays also have some very useful functions built in to speed up our scientific calculations.

Simple function

Let's take a look at the more common operation functions. Before using them, let's construct an array:

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

Calculate the square of the elements in the array:

Np.sqrt (arr) array ([0. , 1., 1.4142, 1.7321, 2., 2.2361, 2.4495, 2.6458, 2.8284, 3.]

The exponential function based on the natural constant e:

Np.exp (arr) array ([1, 2.7183, 7.3891, 20.0855, 54.5982, 148.4132, 403.4288, 1096.6332, 2980.958, 8103.0839])

Take the maximum values of the two arrays to form a new array:

X = np.random.randn (8) y = np.random.randn (8) x 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.01191,1.0048,1.3272,-0.9193]) np.maximum (x Y) array ([0.3313, 1.3497, 0.0699, 0.2467,-0.0119, 1.0048, 1.3272,-0.7539])

Returns the decimal and integer parts of a floating-point array:

Arr = np.random.randn (7) * 5array ([- 7.7455, 0.1109, 3.7918,-3.3026, 4.3129,-0.0502, 0.25]) remainder, whole_part = np.modf (arr) (array ([- 0.7455, 0.1109, 0.7918,-0.3026, 0.3129,-0.0502,0.25]), array ([- 7.,0.3,3.0.25]. 4,-0, 0.]) Vectorized array operation

If you want to perform operations between arrays, the common method is to loop through, but this will be less efficient. So Numpy provides a method of data processing between arrays.

Let's first talk about the np.meshgrid function, which is used to quickly generate grid point coordinate matrices.

First, take a look at the code of a coordinate point:

Import numpy as npimport matplotlib.pyplot as pltx = 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 ()

The X above is a two-dimensional array that represents the position of the X axis of the coordinate points.

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

Take a look at the image drawn:

What is shown above is the six coordinate points combined using the XPerry Y matrix.

The two-dimensional array of XQuery Y above is entered manually, and if there are a large number of points on the coordinates, manual input is definitely not desirable.

So there is the function np.meshgrid. This function can accept two one-dimensional arrays and then generate a two-dimensional XPerry Y coordinate matrix.

The above example can be rewritten as follows:

X = np.array ([0je 1jue 2]) y = np.array ([0je 1]) xs,ys = np.meshgrid (x, y) xs,ys (array ([[0je 1J 2], [0je 1J 2]]), array ([[0,0,0], [1,1,1])

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

With grid coordinates, we can calculate some data based on grid values, such as sqrt (x ^ 2 + y ^ 2) sqrt (x2+y2). Instead of using all the data in the variable matrix, we just need to use the array for operation:

Np.sqrt (xs * 2 + ys * 2)

Results:

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

Because xs and ys themselves are 2 * 3 matrices, the result is also a 2 * 3 matrix.

Conditional logical expression

We can use conditional logical expressions when building 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]) result = [(x if c else y) for x, y, c in zip (xarr, yarr, cond)] result [1.1,2.2,1.3,1.4,2.5]

To make it easier, we can use the where statement:

Result = np.where (cond, xarr, yarr) resultarray ([1.1,2.2,1.3,1.4,2.5])

We can also modify the value of the array according to the conditions of where:

Arr = np.random.randn (4,4) arrarray ([[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])

Above we build a 4 * 4 array.

We can compare the data in where. If it is greater than 0, modify the data to 2, and if less than 0, modify the data to-2:

Np.where (arr > 0,2,-2) array ([[2, 2,-2], [2,-2,-2,-2], [- 2,-2,-2], [2,-2,-2]]) statistical methods

Numpy provides statistical methods such as mean,sum:

Arr = np.random.randn (5,4) arrarr.mean () np.mean (arr) arr.sum ()

You can also count by dimension:

Arr.mean (axis=1) arr.sum (axis=0)

Cumsum carries on the accumulation calculation:

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

Cumprod calculates cumulative multiplication:

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

Any is used to test whether one or more True exists in the array, while all checks that all values in the array are True:

Bools = np.array ([False, False, True, False]) bools.any () Truebools.all () False sort

Arrays can be sorted using sort, which can be sorted by a specific axis in addition to normal sorting:

Arr = np.random.randn (6) arr.sort () array ([- 2.5579,-1.2943,-0.2972,-0.1516, 0.0765, 0.1608]) arr = np.random.randn (5,3) arrarr.sort (1) arrarray ([[- 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])

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

File

You can easily write the array to and read from the file:

Arr = np.arange (10) np.save ('some_array', arr)

The array is stored in the some_array.npy file, which we can read as follows:

Np.load ('some_array.npy')

You can also store multiple arrays without compression:

Np.savez ('array_archive.npz', a=arr, b=arr)

Read:

Arch = np.load ('array_archive.npz') arch [' b']

If you want to compress, you can do this:

Np.savez_compressed ('arrays_compressed.npz', a=arr, b=arr) linear algebra

If we use ordinary operators to operate on a matrix, it is only a simple arithmetic operation of the corresponding elements in the array. If we want to multiply between matrices, we can use dot.

A 2 * 3 matrix dot a 3 * 2 matrix, and finally get a 2 * 2 matrix.

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

Or you can write something like this:

Np.dot (x, y) array ([[28.,64.], [67.181.]])

You can also use the @ symbol:

X @ yarray ([[28.,64.], [67.181]])

Let's take a look at what operations are available:

Product operation:

Operator describes dot (a, b [, out]) matrix dot product linalg.multi_dot (arrays, * [, out]) multiple matrix dot product vdot (a, b) vector dot product inner (a, b) inner product of two arrays outer (a, b [, out]) the outer product of two vectors matmul (x1, x2, / [, out, casting, order, …]) The product of the corresponding bits of two matrices tensordot (a, b [, axes]) calculates the tensor dot product einsum (subscripts, * operands [, out, dtype, …]) along the specified axis. The Einstein summation convention einsum_path (subscripts, * operands [, optimize]) evaluates the lowest cost shrinking order of einsum expressions by considering the creation of intermediate arrays. Power Operation of linalg.matrix_power (a, n) Matrix Kronecker Product of kron (a, b) Matrix

Decomposition operation:

Operator describes linalg.cholesky (a) Cholesky decomposition linalg.qr (a [, mode]) qr factorization of matrix linalg.svd (a [, full_matrices, compute_uv, …]) Singular value decomposition

Eigenvalues and Eigenvectors:

Operation description linalg.eig (a) calculates the eigenvalues and right Eigenvectors of the square matrix. Linalg.eigh (a [, UPLO]) returns the eigenvalues and Eigenvectors of complex Hermitian (conjugate symmetry) or real symmetric matrices. Linalg.eigvals (a) calculates the eigenvalues of a general matrix. Linalg.eigvalsh (a [, UPLO]) calculates the eigenvalues of complex Hermitian (conjugate symmetric) or real symmetric matrices.

Base value:

Operation description 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]) uses the SVD method to return the matrix rank linalg.slogdet (a) of the array to calculate the sign and (natural) logarithm of the array determinant. Trace (a [, offset, axis1, axis2, dtype, out]) returns the sum along the diagonal of the array.

Solve and reverse:

Operation description linalg.solve (a, b) to solve linear matrix equations or linear scalar equations. Linalg.tensorsolve (a, b [, axes]) solves the tensor equation'ax = b 'for x. Linalg.lstsq (a, b [, rcond]) returns the least square solution to the linear matrix equation linalg.inv (a) to calculate the (multiplication) inverse of the matrix. Linalg.pinv (a [, rcond, hermitian]) calculates the (Moore-Penrose) pseudo inverse of the matrix. Linalg.tensorinv (a [, ind]) calculates the "inverse" of the N-dimensional array. Random number

Many times we need to generate random numbers, which are very simple in NumPy:

Samples = np.random.normal (size= (4,4)) samplesarray ([[- 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])

Above, use normal to get a standard normal distribution of 4 × 4 sample array.

Using np.random is much faster than using the random number generator that comes with Python.

Np.random can specify the seeds that generate random numbers:

Np.random.seed (1234)

Numpy.random 's data generation function uses a global random seed. To avoid global state, you can use numpy.random.RandomState to create a random number generator that is isolated from others:

Rng = np.random.RandomState (1234) rng.randn (10) read here, this article "how to use functions in numpy" article has been introduced, want to master the knowledge of this article also need to practice and use in order to understand, if you want to know more about the article, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report