基础

NumPy 提供一个 N-dimensional 的数组,称为 ndarray,是一些相同类型和大小的items的集合体。
在方法中用 axis 来表示 dimensional。
ndarray 类
ndarray 属性
| ndarray.shape | 通常用于获取数组的当前形状,也可用于重塑数组。 | 
|---|---|
| ndarray.size | 数组元素个数 | 
| ndarray.ndim | 数组维度数 | 
| ndarray.nbytes | 数组总字节数 | 
| ndarray.itemsize | 数组元素字节大小 | 
| ndarray.flags | 数组内存分布信息 | 
| ndarray.strides | Tuple of bytes to step in each dimension when traversing an array. | 
| ndarray.data | Python buffer object pointing to the start of the array’s data. | 
| ndarray.base | Base object if memory is from some other object. | 
| 1 | # ndarray.shape | 
ndarray 方法
一般习惯用外部的方法。
索引&切片
| 1 | ### 基础 索引&切片 | 
通用函数 ufunc
广播 Broadcasting
执行 broadcast 的前提在于,两个 ndarray 执行的是 element-wise(按位加减等) 的运算,而不是矩阵乘法的运算,矩阵乘法运算时需要维度之间严格匹配。
broadcasting rules:
- 两个数组shape相等。
- 两个数组shape不相同,但其中一个为1。
| 1 | # 例子: | 
数学运算
| add | Add arguments element-wise. | ||||
|---|---|---|---|---|---|
| subtract | Subtract arguments, element-wise. | ||||
| multiply | Multiply arguments element-wise. | ||||
| divide | Returns a true division of the inputs, element-wise. | ||||
| logaddexp | Logarithm of the sum of exponentiations of the inputs. | ||||
| logaddexp2 | Logarithm of the sum of exponentiations of the inputs in base-2. | ||||
| true_divide | Returns a true division of the inputs, element-wise. | ||||
| floor_divide | Return the largest integer smaller or equal to the division of the inputs. | ||||
| negative | Numerical negative, element-wise. | ||||
| positive | Numerical positive, element-wise. | ||||
| power | First array elements raised to powers from second array, element-wise. | ||||
| remainder | Return element-wise remainder of division. | ||||
| mod | Return element-wise remainder of division. | ||||
| fmod | Return the element-wise remainder of division. | ||||
| divmod | Return element-wise quotient and remainder simultaneously. | ||||
| absolute | Calculate the absolute value element-wise. | ||||
| fabs | Compute the absolute values element-wise. | ||||
| rint | Round elements of the array to the nearest integer. | ||||
| sign | Returns an element-wise indication of the sign of a number. | ||||
| heaviside | Compute the Heaviside step function. | ||||
| conj | Return the complex conjugate, element-wise. | ||||
| exp | Calculate the exponential of all elements in the input array. | ||||
| exp2 | Calculate 2**p for all p in the input array. | ||||
| log | Natural logarithm, element-wise. | ||||
| log2 | Base-2 logarithm of x. | ||||
| log10 | Return the base 10 logarithm of the input array, element-wise. | ||||
| expm1 | Calculate exp(x) - 1for all elements in the array. | ||||
| log1p | Return the natural logarithm of one plus the input array, element-wise. | ||||
| sqrt | Return the non-negative square-root of an array, element-wise. | ||||
| square | Return the element-wise square of the input. | ||||
| cbrt | Return the cube-root of an array, element-wise. | ||||
| reciprocal | Return the reciprocal of the argument, element-wise. | ||||
| gcd | Returns the greatest common divisor of ` | x1 | and | x2 | ` | 
| lcm | Returns the lowest common multiple of ` | x1 | and | x2 | ` | 
三角运算
| sin | Trigonometric sine, element-wise. | 
|---|---|
| cos | Cosine element-wise. | 
| tan | Compute tangent element-wise. | 
| arcsin | Inverse sine, element-wise. | 
| arccos | Trigonometric inverse cosine, element-wise. | 
| arctan | Trigonometric inverse tangent, element-wise. | 
| arctan2 | Element-wise arc tangent of x1/x2choosing the quadrant correctly. | 
| hypot | Given the “legs” of a right triangle, return its hypotenuse. | 
| sinh | Hyperbolic sine, element-wise. | 
| cosh | Hyperbolic cosine, element-wise. | 
| tanh | Compute hyperbolic tangent element-wise. | 
| arcsinh | Inverse hyperbolic sine element-wise. | 
| arccosh | Inverse hyperbolic cosine, element-wise. | 
| arctanh | Inverse hyperbolic tangent element-wise. | 
| deg2rad | Convert angles from degrees to radians. | 
| rad2deg | Convert angles from radians to degrees. | 
对比运算
| greater | Return the truth value of (x1 > x2) element-wise. | 
|---|---|
| greater_equal | Return the truth value of (x1 >= x2) element-wise. | 
| less | Return the truth value of (x1 < x2) element-wise. | 
| less_equal | Return the truth value of (x1 =< x2) element-wise. | 
| not_equal | Return (x1 != x2) element-wise. | 
| equal | Return (x1 == x2) element-wise. | 
| logical_and | Compute the truth value of x1 AND x2 element-wise. | 
|---|---|
| logical_or | Compute the truth value of x1 OR x2 element-wise. | 
| logical_xor | Compute the truth value of x1 XOR x2, element-wise. | 
| logical_not | Compute the truth value of NOT x element-wise. | 
| maximum | Element-wise maximum of array elements. | 
|---|---|
| minimum | Element-wise minimum of array elements. | 
| fmax | Element-wise maximum of array elements. | 
| fmin | Element-wise minimum of array elements. | 
常用功能
数组生成
Ones and zeros
| Ones and zeros | |
|---|---|
| empty | Return a new array of given shape and type, without initializing entries. | 
| empty_like | Return a new array with the same shape and type as a given array. | 
| eye | Return a 2-D array with ones on the diagonal and zeros elsewhere. | 
| identity | Return the identity array. | 
| ones | Return a new array of given shape and type, filled with ones. | 
| ones_like | Return an array of ones with the same shape and type as a given array. | 
| zeros | Return a new array of given shape and type, filled with zeros. | 
| zeros_like | Return an array of zeros with the same shape and type as a given array. | 
| full | Return a new array of given shape and type, filled with fill_value. | 
| full_like | Return a full array with the same shape and type as a given array. | 
| 1 | ## 常用例子 | 
From existing data
| From existing data | |
|---|---|
| array | Create an array. | 
| asarray | Convert the input to an array. | 
| asanyarray | Convert the input to an ndarray, but pass ndarray subclasses through. | 
| ascontiguousarray | Return a contiguous array in memory (C order). | 
| asmatrix | Interpret the input as a matrix. | 
| copy | Return an array copy of the given object. | 
| frombuffer | Interpret a buffer as a 1-dimensional array. | 
| fromfile | Construct an array from data in a text or binary file. | 
| fromfunction | Construct an array by executing a function over each coordinate. | 
| fromiter | Create a new 1-dimensional array from an iterable object. | 
| fromstring | A new 1-D array initialized from text data in a string. | 
| loadtxt | Load data from a text file. | 
| 1 | ## 常用例子 | 
Numerical ranges
| Numerical ranges | |
|---|---|
| arange | Return evenly spaced values within a given interval. | 
| linspace | Return evenly spaced numbers over a specified interval. | 
| logspace | Return numbers spaced evenly on a log scale. | 
| geomspace | Return numbers spaced evenly on a log scale (a geometric progression). | 
| meshgrid | Return coordinate matrices from coordinate vectors. | 
| mgrid | nd_grid instance which returns a dense multi-dimensional “meshgrid”. | 
| ogrid | nd_grid instance which returns an open multi-dimensional “meshgrid”. | 
| 1 | ## 常用例子 | 
数组操作
Changing array shape
| Changing array shape | |
|---|---|
| reshape | Gives a new shape to an array without changing its data. | 
| ravel | Return a contiguous flattened array. | 
| ndarray.flat | A 1-D iterator over the array. | 
| ndarray.flatten | Return a copy of the array collapsed into one dimension. | 
| 1 | ## 常用函数 | 
Transpose-like operations
| Transpose-like operations | |
|---|---|
| moveaxis | Move axes of an array to new positions. | 
| rollaxis | Roll the specified axis backwards, until it lies in a given position. 可用moveaxis实现。 | 
| swapaxes | Interchange two axes of an array. | 
| ndarray.T | Same as self.transpose(), except that self is returned if self.ndim < 2. | 
| transpose | Permute the dimensions of an array. | 
| 1 | ## 常用例子 | 
Changing number of dimensions
| Changing number of dimensions | |
|---|---|
| atleast_1d | Convert inputs to arrays with at least one dimension. | 
| atleast_2d | View inputs as arrays with at least two dimensions. | 
| atleast_3d | View inputs as arrays with at least three dimensions. | 
| broadcast | Produce an object that mimics broadcasting. | 
| broadcast_to | Broadcast an array to a new shape. | 
| broadcast_arrays | Broadcast any number of arrays against each other. | 
| expand_dims(a, axis) | Expand the shape of an array. | 
| squeeze(a[, axis]) | Remove single-dimensional entries from the shape of an array. | 
| 1 | ## 常用函数 | 
Changing kind of array
| Changing kind of array | |
|---|---|
| asarray | Convert the input to an array. | 
| asanyarray | Convert the input to an ndarray, but pass ndarray subclasses through. | 
| asmatrix | Interpret the input as a matrix. | 
| asfarray | Return an array converted to a float type. | 
| asfortranarray | Return an array laid out in Fortran order in memory. | 
| ascontiguousarray | Return a contiguous array in memory (C order). | 
| asarray_chkfinite | Convert the input to an array, checking for NaNs or Infs. | 
| asscalar | Convert an array of size 1 to its scalar equivalent. | 
| require | Return an ndarray of the provided type that satisfies requirements. | 
| 1 | ## 常用函数 | 
Joining arrays
| Joining arrays | |
|---|---|
| concatenate | Join a sequence of arrays along an existing axis. | 
| stack | Join a sequence of arrays along a new axis. | 
| column_stack | Stack 1-D arrays as columns into a 2-D array. | 
| dstack | Stack arrays in sequence depth wise (along third axis). | 
| hstack | Stack arrays in sequence horizontally (column wise). | 
| vstack | Stack arrays in sequence vertically (row wise). | 
| block | Assemble an nd-array from nested lists of blocks. | 
| 1 | ### 常用函数 | 
Splitting arrays
| Splitting arrays | |
|---|---|
| split | Split an array into multiple sub-arrays. | 
| array_split | Split an array into multiple sub-arrays. | 
| dsplit | Split array into multiple sub-arrays along the 3rd axis (depth). | 
| hsplit | Split an array into multiple sub-arrays horizontally (column-wise). | 
| vsplit | Split an array into multiple sub-arrays vertically (row-wise). | 
| 1 | ### 常用函数 | 
输入输出
NumPy binary files (NPY, NPZ)
| NumPy binary files (NPY,NPZ) | |
|---|---|
| load | Load arrays or pickled objects from .npy,.npzor pickled files. | 
| save | Save an array to a binary file in NumPy .npyformat. | 
| savez | Save several arrays into a single file in uncompressed .npzformat. | 
| savez_compressed | Save several arrays into a single file in compressed .npzformat. | 
| 1 | ### 常用函数 | 
Text files
| Text files | |
|---|---|
| loadtxt | Load data from a text file. | 
| savetxt | Save an array to a text file. | 
| genfromtxt | Load data from a text file, with missing values handled as specified. | 
| fromregex | Construct an array from a text file, using regular expression parsing. | 
| fromstring | A new 1-D array initialized from text data in a string. | 
| ndarray.tofile | Write array to a file as text or binary (default). | 
| ndarray.tolist | Return the array as a (possibly nested) list. | 
| 1 | ### 常用函数 | 
Text formatting options
| Text formatting options | |
|---|---|
| set_printoptions | Set printing options. | 
| get_printoptions | Return the current print options. | 
| set_string_function | Set a Python function to be used when pretty printing arrays. | 
| printoptions | Context manager for setting print options. | 
| 1 | ### 常用例子 | 
随机采样(numpy.random)
Simple random data
| Simple random data | |
|---|---|
| rand | Random values in a given shape. | 
| randn | Return a sample (or samples) from the “standard normal” distribution. | 
| randint | Return random integers from low (inclusive) to high (exclusive). | 
| random_integers | Random integers of type np.int between low and high, inclusive. | 
| random_sample | Return random floats in the half-open interval [0.0, 1.0). | 
| random | Return random floats in the half-open interval [0.0, 1.0). | 
| ranf | Return random floats in the half-open interval [0.0, 1.0). | 
| sample | Return random floats in the half-open interval [0.0, 1.0). | 
| choice | Generates a random sample from a given 1-D array | 
| bytes | Return random bytes. | 
| 1 | ### 常用函数 | 
#### Permutations
| Permutations | 随机排列 | 
|---|---|
| shuffle | Modify a sequence in-place by shuffling its contents. | 
| permutation | Randomly permute a sequence, or return a permuted range. | 
| 1 | ### 常用函数 | 
Distributions
| Distributions | 输入各个分布的参数,获得相应shape的样本。 | 
|---|---|
| beta | Draw samples from a Beta distribution. | 
| binomial | Draw samples from a binomial distribution. | 
| chisquare | Draw samples from a chi-square distribution. | 
| dirichlet | Draw samples from the Dirichlet distribution. | 
| exponential | Draw samples from an exponential distribution. | 
| f | Draw samples from an F distribution. | 
| gamma | Draw samples from a Gamma distribution. | 
| geometric | Draw samples from the geometric distribution. | 
| gumbel | Draw samples from a Gumbel distribution. | 
| hypergeometric | Draw samples from a Hypergeometric distribution. | 
| laplace | Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay). | 
| logistic | Draw samples from a logistic distribution. | 
| lognormal | Draw samples from a log-normal distribution. | 
| logseries | Draw samples from a logarithmic series distribution. | 
| multinomial | Draw samples from a multinomial distribution. | 
| multivariate_normal | Draw random samples from a multivariate normal distribution. | 
| negative_binomial | Draw samples from a negative binomial distribution. | 
| noncentral_chisquare | Draw samples from a noncentral chi-square distribution. | 
| noncentral_f | Draw samples from the noncentral F distribution. | 
| normal | Draw random samples from a normal (Gaussian) distribution. | 
| pareto | Draw samples from a Pareto II or Lomax distribution with specified shape. | 
| poisson | Draw samples from a Poisson distribution. | 
| power | Draws samples in [0, 1] from a power distribution with positive exponent a - 1. | 
| rayleigh | Draw samples from a Rayleigh distribution. | 
| standard_cauchy | Draw samples from a standard Cauchy distribution with mode = 0. | 
| standard_exponential | Draw samples from the standard exponential distribution. | 
| standard_gamma | Draw samples from a standard Gamma distribution. | 
| standard_normal | Draw samples from a standard Normal distribution (mean=0, stdev=1). | 
| standard_t | Draw samples from a standard Student’s t distribution with df degrees of freedom. | 
| triangular | Draw samples from the triangular distribution over the interval [left, right]. | 
| uniform | Draw samples from a uniform distribution. | 
| vonmises | Draw samples from a von Mises distribution. | 
| wald | Draw samples from a Wald, or inverse Gaussian, distribution. | 
| weibull | Draw samples from a Weibull distribution. | 
| zipf | Draw samples from a Zipf distribution. | 
排序,搜索,统计
Sorting
| Sorting | |
|---|---|
| sort | Return a sorted copy of an array. | 
| lexsort | Perform an indirect stable sort using a sequence of keys. | 
| argsort | Returns the indices that would sort an array. | 
| ndarray.sort | Sort an array, in-place. | 
| msort | Return a copy of an array sorted along the first axis. | 
| sort_complex | Sort a complex array using the real part first, then the imaginary part. | 
| partition | Return a partitioned copy of an array. | 
| argpartition | Perform an indirect partition along the given axis using the algorithm specified by the kindkeyword. | 
| 1 | ### 常用函数 | 
Searching
| Searching | |
|---|---|
| argmax | Returns the indices of the maximum values along an axis. | 
| nanargmax | Return the indices of the maximum values in the specified axis ignoring NaNs. | 
| argmin | Returns the indices of the minimum values along an axis. | 
| nanargmin | Return the indices of the minimum values in the specified axis ignoring NaNs. | 
| argwhere | Find the indices of array elements that are non-zero, grouped by element. | 
| nonzero | Return the indices of the elements that are non-zero. | 
| flatnonzero | Return indices that are non-zero in the flattened version of a. | 
| where | Return elements, either from x or y, depending on condition. | 
| searchsorted | Find indices where elements should be inserted to maintain order. | 
| extract | Return the elements of an array that satisfy some condition. | 
| 1 | ### 常用函数 | 
Counting
| counting | |
|---|---|
| count_nonzero(a[, axis]) | Counts the number of non-zero values in the array a | 
| 1 | # .cout_nonzero() 返回非零值的个数。 |