PS: This blog digest from the Chinese University of the curriculum "Python data analysis and display," recommended just the beginner 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. Its integration of C/c++.fortran code tools, but also scipy, pandas and other basic
. Ndim: Dimensions
. Shape: Scale of each dimension (2,5)
. Size: Number of elements 10
. Dtype: Type of Element Dtype (' int32 ')
. itemsize: The size of each element, in bytes, of 4 bytes per element
Ndarray Creation of arrays
Np.arange (n); The Ndarray type of the element from 0 to N-1
Np.ones (SHAPE): Generates all 1
Np.zeros (shape), Ddtype = Np.int32): Generates full 0 of int32 type
Np.full (Shape, Val): Generate all Val
Np.eye (n): Generating the Unit matrix
Np.ones_like (a): Generates an array of all 1 by the shape of the array a
Np.zeros_like (a): similarly
Np.full_like (A, Val): similarly
Np.linspace (1,10,4): Generates an array based on spacing from start to end data
Np.linspace (1,10,4, endpoint = False): Endpoint Indicates whether 10 is the generated element
Np.concatenate (): Concatenation of multiple arrays
- Dimension transformations of arrays
. Reshape (SHAPE): Does not change the current array, generated by shape
. Resize (Shape): Changes the current array, generated by shape
. swapaxes (Ax1, AX2): Swap two dimensions
. Flatten (): Descending dimension of an array, returning a collapsed one
- Type transformation of an array
Conversion of data types: A.astype (new_type): Eg, A.astype (np.float)
Array-to-list conversions: A.tolist ()
Index and slice of an array
- One-dimensional array slicing
A = Np.array ([9, 8, 7, 6, 5,])
A[1:4:2]–> Array ([8, 6]): a[start Number: termination number (not included): Step length]
- Multidimensional array index
A = Np.arange. Reshape ((2, 3, 4))
A[1, 2, 3] represents a number on 3 dimensions, and the number of each dimension is separated by commas
- Multidimensional array slicing
A [:,:,:: 2] By default, the expression starts with the No. 0 element and the last element
Operations on arrays
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): Calculates the logarithm of the natural logarithm, 10, and 2 of each element
Np.ceil (a) Np.floor (a): Calculates the ceiling value of each element, floor value (ceiling rounding up, floor down rounding)
Np.rint (a): Rounding each element
NP.MODF (a): Returns the fractional and integer portions of each element of an array as two independent arrays
Np.exp (a): Calculates 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 the element level
Np.minimum (A, B) np.fmin (): Minimum value
Np.mod (A, B): modulo operations at the element level
Np.copysign (A, B): assigns the symbol of each element in B to the corresponding element of array a
CSV (comma-separated value, comma-separated values) can store only one and two-dimensional arrays
Np.savetxt (frame, array, fmt= '%. 18e ', delimiter = None): Frame is a file, string, etc., which can be a compressed file of. gz. bz2; array represents the arrays deposited; FMT represents the format of the element eg:% 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, Dtype: Data type, read data in such Delimiter: Split string, default is space; Unpack: If true, read-in properties are written to separate variables.
Access to multidimensional data
A.tofile (frame, sep= ", format= '%s '): Frame: File, String, Sep: Data split string, if empty string, write to file binary; Format:: Write Data 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: The data read is stored in this type; count: reads the number of elements, 1 means the entire file is read; Sep: Data Splits the string, if it is an empty string, writes the file binary
Ps:a.tofile () and Np.fromfile () are used together to know the type and dimension of the data.
Np.save (frame, array): Frame: File name with. npy extension, compression extension. npz; array array variable
Np.load (fname): Frame: File name with. npy extension, Compression extension
Np.save () and np.load () are used without having to consider data types and dimensions themselves.
- NumPy Random number function
NumPy's Random sub-Library
Rand (D0, D1, ..., dn): Each element is a floating-point number [0, 1], subject to uniform distribution
Randn (D0, D1, ..., DN): standard normal distribution
Randint (Low, high, (Shape)): Creates a random integer or an array of integers by shape, with a range of [low, high]
Seed (s): Random number Seed
Shuffle (a): randomly arranged according to the first axis of array A, changing the array a
Permutation (a): randomly arranged according to the first axis of array A, but does not change the original array, will generate a new array
Choice (a[, size, replace, p]): Extracts elements from a one-dimensional array A with probability p, forms a new array of size shapes, replace indicates whether elements can be reused, and defaults to false.
eg
Replace = False, the selected element will no longer be selected
Uniform (low, high, size): Produces an evenly distributed array with a starting value of Low,high as the ending value and size as the shape
Normal (loc, scale, size): Generates an array of normal distributions, loc is mean, scale is standard deviation, size is shape
Poisson (Lam, size): Array of Poisson distributions, probability of Lam random events, size as shape
eg:a = Np.random.uniform (0, Ten, (3, 4)) A = Np.random.normal (10, 5, (3, 4))
- Statistical functions of NumPy
Sum (A, Axis = None): Calculates the sum of the related elements of array A, axis is an integer or tuple, depending on axis axis
Mean (A, Axis = None): In the same vein, calculate the average
Average (A, axis =none, Weights=none): Calculates the weighted average of the related elements of the array a given axis axis
STD (A, Axis = None): Similarly, calculate standard deviation
var (A, Axis = None): Calculate variance
Eg:np.mean (A, Axis =1): Averaging data for the second dimension of array a
A = Np.arange (a). Reshape (3, 5)
Np.average (A, axis =0, weights =[10, 5, 1]): Weighted average for the first dimensions of a, weight in weights, and attention to the first dimension of a
Min (a) max (a): calculates minimum and maximum values for array a
Argmin (a) Argmax (a): Calculates the subscript for the minimum and maximum values of array A (note: is a one-dimensional subscript)
Unravel_index (Index, shape): Converts one-dimensional subscript index to multidimensional subscript according to shape
PTP (a): Calculates the difference between the maximum and minimum values of the array a
Median (a): Calculates the median of the elements 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)
- The gradient function of NumPy
Np.gradient (a): Calculates the gradient of an element in array A, when F is multidimensional, returns the gradient of each dimension
Discrete gradient: The y-axis value of the XY axis for a continuous three x-axis coordinate: A, B, c where the gradient of B is (C-A)/2
The gradient of C is: (c-b)/1
When a two-dimensional array, np.gradient (a) obtains 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 ') indicates a grayscale image
NumPy operations in Python