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 NumPy in Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the relevant knowledge of how NumPy is used in Python, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will have something to gain after reading this article on how to use NumPy in Python. Let's take a look at it.

Introduction

NumPy is the most important basic package for Python numerical computation, and most packages that provide scientific computation are built on the basis of NumPy's array. NumPy itself does not provide much advanced data analysis capabilities, and understanding NumPy arrays and array-oriented computing will help you use tools such as Pandas more efficiently.

Although NumPy provides a general computational basis for numerical data processing, most readers may want to use Pandas as the basis for statistical and analytical work, especially when dealing with tabular data.

Some of the functions of NumPy are as follows:

Ndarray, a fast and space-saving multidimensional array with vector arithmetic operations and complex broadcasting capabilities.

A standard mathematical function used to perform fast operations on an entire set of data (no need to write a loop).

Tools for reading and writing disk data and tools for manipulating memory-mapped files.

Linear algebra, random number generation and Fourier transform functions.

A C API for integrating code written in C, C++, Fortran, and other languages.

NumPy is particularly important for numerical computation because it can efficiently process data from large arrays. This is because:

NumPy arrays use less memory than Python's built-in sequences.

NumPy can perform complex calculations on an entire array without the need for Python's for loop.

Use the following formatting convention to introduce the NumPy package:

Import numpy as np

Ndarray:N dimension array object of NumPy

The most important thing about NumPy is its N-dimensional array object (that is, ndarray), where all elements must be of the same type. This object is a fast and flexible big data set container, which can be used to perform mathematical operations on the whole block of data, and its syntax is the same as that between scalar elements.

Create ndarray

Use the np.array (list/tuple, dtype=np.float32) function to produce a new ndarray object that contains incoming data.

The first parameter is the tuple, the list (the same data type), and the second parameter is the data type in the ndarray array. When the second parameter is empty, NumPy specifies a type based on the data.

The return value is in the form of [], and the elements are separated by spaces.

In [20]: arr1 = np.array ([6,7.5,8,0,1]) # create In [21]: pring (arr1) Out [21]: [6,7.5,8., 0. , 1.] # NumPy specifies the float type In [23]: arr2 = np.array ([[1,2,3,4], [5,6,7,8], (1.2,2.3)]) In [24]: pring (arr2) Out [24]: [1,2,3,4] [5,6,7,8] (1.2,2.3)]

Use the built-in functions in NumPy

Np.arange (begin,end,step,dtype=np.float32): begin is the start value of the element (inclusive), end is the end value of the element (not included), step is the step size (default is 1), and dtype is the element type. If there is only one parameter n, it is from 0 to nmur1; if there are two parameters n and m, it is from n to mmur1.

Np.linspace (begin,end,number): creates an array of number elements with an average interval between the specified start value (inclusive) and end value (inclusive)

Np.ones (shape): generates an all-1 array based on shape. Shape is a tuple type, such as (2)

Np.zeros (shape): generates an all-zero array based on shape. Shape is a tuple type, such as (2mem3pd4).

Np.full (shape,val): generates an array based on shape, and each element value is val

Np.eye (n): create a square naught unit matrix with a diagonal of 1 and the rest of 0

Np.ones_like (a): generates an all-1 array based on the shape of the array a

Np.zeros_like (a): generates an all-zero array based on the shape of the array a

Np.full_like (ajar Val): generate an array whose value of each element is val based on the shape of the array a

Np.concatenate () combines two or more numbers into a new array.

In [30]: arr3 = np.zeros ((3,6) In [31]: print (arr3) Out [30]: [0, 0, 0, 0, 0.] [0, 0, 0, 0, 0.] [0, 0, 0, 0, 0.]

Read data from disk to create a ndarray array and save the ndarray array to disk (in most cases you will use pandas or other tools to load text or tabular data)

Np.load (fname)

Fname: file name with .npy extension and .npz compression extension

Np.save (fname, array) or np.savez (fname, array)

Fname: file name with .npy extension and .npz compression extension

Array: array variables

Properties of ndarray array objects

.ndim: rank, which is the number of axes or dimensions

.shape: the scale of the ndarray object. For matrices, n rows and m columns

.size: the number of elements of the ndarray object, which is equal to the value of ncm in .shape

.dtype: the element type of the ndarray object

.itemsize: the size of each element in the ndarray object, in bytes

Type and Dimension Transformation of ndarray Array objects

.astype (np.float64): converts ndarray array elements from one type to another and returns a new array. If you convert a floating-point number to an integer, the decimal part will be truncated and deleted. (type transformation)

Reshape (shape): returns an array of new shape dimensions (dimension transformation) without changing the original array elements.

.resize (shape): consistent with .reshape () function, but modifies the original array (dimension transformation)

.swapaxes (ax1,ax2) swaps two dimensions out of an array of n dimensions (dimension transformation)

.flatten (): reduces the dimension of the array and returns the folded one-dimensional array, with the original array unchanged (dimension transformation).

.tolist (): converts an N-dimensional array to a list (dimension transformation)

Indexes and slices of ndarray arrays

The operation of ndarray array

The operation between an array and a scalar acts on every element of the array.

Any arithmetic operation between arrays of the same size applies the operation to the element level

Comparison operations between arrays of the same size apply the operation to the element level and generate an array of Boolean values

Np.abs (arr)\ np.fabs (arr): calculates the absolute value of each element of the array arr

Np.sqrt (arr): calculates the square root of each element of the array arr

Np.square (arr): calculates the square of each element of the array arr

Np.log (arr)\ np.log10 (arr)\ np.log2 (arr): calculate the natural logarithm, 10 base logarithm and 2 base logarithm of each element of the array arr

Np.ceil (arr)\ np.floor (arr): calculates the floor or floor value of each element of the array arr

Np.rint (arr) calculates the rounded values of the elements of the array arr

Np.modf (arr) returns the decimal and integer parts of each element of the array arr as two separate arrays

Np.cos (arr)\ np.cosh (arr)\ np.sin (arr)\ np.sinh (arr)\ np.tan (arr)\ np.tanh (arr) calculates the ordinary and hyperbolic trigonometric functions of the elements of the array arr

Np.exp (arr) calculates the index values of each element of the array arr

Np.sign (arr) calculates the symbolic values of the elements of the array arr, 1 (+), 0,-1 (-)

Using ndarray for data processing

Sort

The ndarray array is sorted by the .sort () function, and the axis number is passed in the multi-dimensional array.

Random number function of NumPy

Np.random.rand: create random array according to d0-dn, floating point number, [0meme 1), uniform distribution.

Np.random.randn: create random array according to d0-dn, standard normal distribution

Np.random.randint (low [, high,shape]): creates a random integer or array of integers based on shape, with a range of [low, high)

Np.random.seed (s): random number seed, s is the given species

Np.random.shuffle (a): array x is changed according to the first axis of array a

Np.random.permutation (a): generates a new disordered array based on the first axis of array a without changing the array x

Np.random.choice (a [, size,replace,p]): extract elements from one-dimensional array a with probability p to form a new size-shaped array replace to indicate whether elements can be reused. The default is False.

Np.random.uniform (low,high,size): produces an array with uniform distribution, low start value, high end value, size shape

Np.random.normal (loc,scale,size): generate arrays with normal distribution, loc mean, scale standard deviation, size shape

Np.random.poisson (lam,size): generates an array with Poisson distribution, lam random event incidence, size shape

Statistical class functions of NumPy

Np.sum (a, axis=None): calculates the sum of array a related elements, axis integers or tuples based on a given axis axis

Np.mean (a, axis=None): calculates expectations of array a-related elements, axis integers, or tuples based on a given axis axis

Np.average: calculates the weighted average of the array a related elements based on the given axis axis

Np.std (a, axis=None): calculates the standard deviation of array a related elements based on a given axis axis

Np.var (a, axis=None): calculates the variance of array a related elements based on a given axis axis

Np.min (a)\ max (a): calculates the minimum and maximum values of elements in the array a

Np.argmin (a)\ argmax (a): subscript after calculating the minimum and maximum values of elements in array a by one dimension

Np.unravel_index (index, shape): convert one-dimensional subscript index to multidimensional subscript according to shape

Np.ptp (a): calculates the difference between the maximum and minimum values of elements in the array a

Np.median (a): calculates the median of elements in array a (median)

Gradient function of NumPy

Gradient: the rate of change between continuous values, that is, slope

The Y axis values corresponding to three consecutive X coordinates of the XY axis: a, b, c, where the gradient of b is: (Cmura) / 2

Np.gradient (f): calculates the gradient of elements in the array f, and returns the gradient of each dimension when f is multidimensional

This is the end of the article on "how to use NumPy in Python". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use NumPy in Python". If you want to learn more, you are 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