Python's NumPy library common function Encyclopedia

Source: Internet
Author: User
Tags bz2 natural logarithm square root unpack

Recently learned Python, only to find that the original Python in the various libraries is the big head. So I found the learning materials to summarize the functions commonly used in NumPy library, and bring the annotation. Here to share with you, for the library of learning, or use the time to check again, there is no need to memorize.
PS: This blog digest from the Chinese University of Mu course "Python Data analysis and display", recommended just beginners to learn, this is a very good introductory video.

NumPy is a scientific computing library, is a powerful n-dimensional array object Ndarray, is a broadcast function function. The tool that integrates C/c++.fortran code is the foundation of scipy, pandas, etc.

. Ndim: Dimensions
. Shape: Scales of each dimension (2,5)
. Size: Number of elements 10
. Dtype: The type of Element Dtype (' int32 ')
. itemsize: Size of each element, in bytes, 4 bytes per element
Creation of Ndarray arrays
Np.arange (n); Ndarray types of elements from 0 to n-1
Np.ones (SHAPE): Generate all 1
Np.zeros ((shape), Ddtype = Np.int32): Generating all 0 of the Int32 type
Np.full (Shape, Val): All Val-generated
Np.eye (n): Generating the Unit matrix

Np.ones_like (a): Generates an array of all 1 by the shape of array a
Np.zeros_like (a): similarly
Np.full_like (A, Val): similarly

Np.linspace (1,10,4): Generate arrays based on spacing between start and start data
Np.linspace (1,10,4, endpoint = False): Endpoint Indicates whether 10 is a generated element
Np.concatenate (): Dimension transformation of an array

. Reshape (SHAPE): Do not change the current array, generated by shape
. Resize (Shape): Changes to the current array, generated by shape
. swapaxes (Ax1, AX2): Swap two dimensions
. Flatten (): dimensionality reduction of arrays, returning the type transformation of an array of folds

Conversion of data types: A.astype (new_type): Eg, A.astype (np.float)
Array conversion to list: A.tolist ()
Indexed and sliced one-dimensional array slices for arrays

A = Np.array ([9, 8, 7, 6, 5,])
A[1:4:2]–> Array ([8, 6]): a[start Number: End number (not included): Step] Multidimensional array index

A = Np.arange. Reshape ((2, 3, 4))
A[1, 2, 3] represents the number on 3 dimensions, and the number of each dimension separates multidimensional array slices with commas

A [:,:,:: 2] By default, the representation begins with the No. 0 element, to the last element
The operation of an array
Np.abs (a) Np.fabs (a): Take the absolute value of each element
Np.sqrt (a): Calculates the square root of each element
Np.square (a): Calculates the square of each element
Np.log (a) np.log10 (a) np.log2 (a): Calculate the natural logarithm of each element, the logarithm of 10, 2 as the base
Np.ceil (a) Np.floor (a): Calculates the ceiling value of each element, floor value (ceiling rounding up, floor rounding down)
Np.rint (a): Rounding the Elements
NP.MODF (a): Returns the decimal and integer portions of the array elements in two separate arrays
Np.exp (a): Calculate the exponential value of each element
Np.sign (a): Calculates the symbolic value of each element 1 (+), 0,-1 (-)
.
Np.maximum (A, B) Np.fmax (): compare (or calculate) the maximum value of an element level
Np.minimum (A, B) np.fmin (): Take the minimum value
Np.mod (A, B): Modular operations at the element level
Np.copysign (A, b): CSV file access that assigns the symbols of each element in B to the corresponding element data of array a

CSV (comma-separated value, comma separated values) can only store one and two dimensional arrays

Np.savetxt (frame, array, fmt= '%. 18e ', delimiter = None): Frame is a file, string, etc., can be a compressed file of. gz. bz2; D. 2f%. 18e; Delimiter: Split string, default is space
Eg:np.savetxt (' A.csv ', A, fmt=%d, delimiter = ', ')

Np.loadtxt (frame, dtype=np.float, delimiter = None, unpack = False): Frame is a file, string, etc., can be a compressed file of. gz. BZ2: Data type, read data in this class Delimiter: Split string, default is space; Unpack: If true, the read attributes are written to different variables respectively.
Access to multidimensional data
A.tofile (frame, sep= ', format= '%s '): Frame: File, String, Sep: Data-splitting string, if empty string, write file as binary; Format:: Writing data in formats
Eg:a = Np.arange. Reshape (5, 10, 2)
A.tofile ("B.dat", sep= ",", format= '%d ')

Np.fromfile (frame, dtype = float, count=-1, sep= '): Frame: file, string; Dtype: Read data stored in this type; count: reads the number of elements,-1 reads the entire file; Sep: Data Split string, if empty string, write file as binary

Ps:a.tofile () and Np.fromfile () are used together to know the type and dimension of the data.

Np.save (frame, array): frame: filename, with. npy extension, compressed extension. NPZ array for array variables
Np.load (fname): frame: filename, with. npy as the extension, compressing the extension with the name

When Np.save () and np.load () are used, you do not have to consider the data types and dimensions yourself. NumPy Random number function

NumPy Random Sub-Library

Rand (D0, D1, ..., dn): Each element is a floating-point number of [0, 1) that is uniformly distributed
Randn (D0, D1, ..., DN): standard normal distribution
Randint (Low, high, (Shape)): Creates a random integer or array of integers by shape, with a range of [low, high]
Seed (s): Random number of seeds

Shuffle (a): random permutation based on the first axis of array A, changing array a
Permutation (a): Random arrangement based on the first axis of array a, but without altering the original array, a new array will be generated
Choice (a[, size, replace, p]): Extracts an element from a one-dimensional array of probability p, forms a new array of size shapes, and replace indicates whether the element can be reused and false by default.
eg
Replace = False, the selected element will no longer be selected

Uniform (low, high, size): An evenly distributed array with a starting value of Low,high as the ending value and size as the shape
Normal (loc, scale, size): An array that produces a normal distribution, loc is a mean, scale is a standard deviation, and the size is a shape
Poisson (Lam, size): An array of Poisson distributions, the probability of the occurrence of Lam random events, size as the shape
eg:a = Np.random.uniform (0, (3, 4)) A = Np.random.normal (5, (3, 4)) NumPy statistical function

Sum (A, Axis = None): Calculates the sum of the associated elements of an array by a given axis axis, axis is an integer or tuple
Mean (A, Axis = None): Similarly, calculate the average
Average (A, axis =none, Weights=none): Calculates the weighted average of an associated element of an array based on a given axis axis
STD (A, Axis = None): Similarly, calculating standard deviation
var (A, Axis = None): Calculating variance
Eg:np.mean (A, Axis =1): Data for the second dimension of array A is averaged
A = Np.arange. Reshape (3, 5)
Np.average (A, axis =0, weights =[10, 5, 1]): Weighted average for the first dimension of a, weight in weights, attention to match the first dimension of a

Min (a) max (a): Calculates the minimum and maximum values of array a
Argmin (a) Argmax (a): computes subscript for the minimum and maximum value of array A (note: is a one-dimensional subscript)
Unravel_index (Index, shape): Convert one-dimensional subscript index to multidimensional subscript according to shape
PTP (a): Calculates the difference between the maximum and minimum values of array a
Median (a): computes the median of an element in array a (median)
EG:A = [[15, 14, 13],
[12, 11, 10]]
Np.argmax (a) –> 0
Np.unravel_index (Np.argmax (a), A.shape) –> (0,0) numpy gradient function

Np.gradient (a): Calculates the gradient of elements in array A, F is multidimensional, returns the gradient of each dimension
Discrete gradient: XY axis three consecutive x axis coordinates corresponding to the y-axis value: A, B, c where the gradient of B is (C-A)/2
And the gradient of C is: (c-b)/1

When a two-dimensional array, np.gradient (a) gets two arrays, the first array corresponds to the gradient of the outermost dimension, and the second array corresponds to the gradient of the second-level dimension.
Representation and transformation of images

PIL, Python Image Library
From PIL import Image
Image is a class (object) that represents an image in the PIL library

im = Np.array (Image.open (". jpg"))

im = Image.fromarray (b.astype (' uint8 ')) # Build
Im.save ("path. jpg") # Save

im = Np.array (Image.open (". jpg"). Convert (' l ') # convert (' l ') representation to grayscale

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.