NumPy Provides:
- An array object of arbitrary homogeneous items
- Fast mathematical operations over arrays
- Linear Algebra, Fourier Transforms, Random Number Generation
- Tools for integrating C/C++ and Fortran code
import numpy as np
或from numpy import *
: 常用加载numpy语句
help(np.zeros)
可以查询帮助,按空格跳下页.
np.info(np.add)
也可以获得帮助,像np.add用c写的只能用这种方法获得帮助(因为没有docstring).
np.lookfor('keyword')
也可以进行帮助搜索查询
ndarray 数组模块
NumPy数组ndarray是一个多维紧密数组对象,由两部分组成:(1)实际的数据; (2)描述这些数据的元数据. 大部分操作仅针对于元数据,而不改变底层实际的数据。NumPy数组的下标从0开始。同一个NumPy数组中所有元素的类型必须是相同的。
支持像多维列表一样的索引,切片和赋值.
使用加减乘除乘幂都是针对每个元素执行. 使用比较运算符会对每个元素进行条件比较, 返回全是True/False的数组.
ndarray常见属性 a.prop :
- ndim:数组的维数(即数组轴的个数),等于秩。最常见的为二维数组(矩阵)。
- shape:数组的维度。为一个表示数组在每个维度上大小的整数元组。ndarray.shape返回一个元组,这个元组的长度就是维度的数目,即ndim属性。
- size:数组元素的总个数,等于shape属性中元组元素的乘积。
- dtype:表示数组中元素类型的对象,可使用标准的Python类型创建或指定dtype。所有类型可通过set(np.typeDict.values())查看
- itemsize:数组中每个元素的字节大小。例如,一个元素类型为float64的数组itemsiz属性值为8(float64占用64个bits,每个字节长度为8,占用8个字节),又如一个元素类型为complex32的数组item属性为4。
- data:包含实际数组元素的缓冲区地址,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。
- nbytes: 这个array的总字节数(=itemsize*size)
- real: 代表一个array中所有元素的实数部分
- imag: 代表一个array中所有元素的虚数部分
- flat: 将这个array整理成一维的,可以索引的一系列的元素组合。它实际上是通过iterator实现的,我们可以通过for x in array.flat来取得到所有的元素
- T: 转置矩阵,同transpose()方法返回值
ndarray常见方法: a.func(..) :
以下方法基本可以利用np.func(a,...)
等价实现,a就是数组对象.
- ravel([order]) : 展平为1维数组.
- reshape(newshape, order=’C’) : 重整数组的形状,形状为整数或者元组.-1可以表示根据数据量调整该值.例如6数据(3,-1)等价于(3,2).
- resize(newshape, refcheck=True): 也是改变array的形态。不同的是,resize是直接修改这个对象的,而reshape则会生成一个新的对象
- transpose(axes=None) : 矩阵转置.transpose()等价于
a.T
. - tolist(): 将数据转为列表,不同于list(a)会把降维数组作为元素转到列表中.
- tostring(order=’C’): 将数组数据转为字符串.
swapaxes(): 将n个维度中任意两个维度(坐标轴)进行调换 flatten(): 复制一个一维的array出来 item(*args): 取得某一位置的元素 dump(file): 将这个对象序列化至文件。同cPickle中的dump作用 dumps(): 将序列化的结果通过字符串加以输出
统计
- max():取得所有元素中的最大值
- min():取得最小值。还有一点值得说,就是max、min这些函数都可以针对某一坐标轴(具体维度)进行运算,例如array.max(axis=0),就在0坐标上求最大值
- sum():求和
- cumsum():求累计和
- prod():求所有元素之积
- cumprod():求累计积 mean():求平均数
- all(axis=None, out=None):如果所有元素都为真,那么返回真;否则返回假
- any(axis=None, out=None):只要有一个元素为真则返回真
常见参数
Data type | Description |
---|---|
bool | Boolean (True or False) stored as a byte |
int | Platform integer (normally either int32 or int64) |
int8 | Byte (-128 to 127) |
int16 | Integer (-32768 to 32767) |
int32 | Integer (-2147483648 to 2147483647) |
int64 | Integer (9223372036854775808 to 9223372036854775807) |
uint8 | Unsigned integer (0 to 255) |
uint16 | Unsigned integer (0 to 65535) |
uint32 | Unsigned integer (0 to 4294967295) |
uint64 | Unsigned integer (0 to 18446744073709551615) |
float | Shorthand for float64. |
float32 | Single precision float: sign bit, 8 bits exponent, 23 bits mantissa |
float64 | Double precision float: sign bit, 11 bits exponent, 52 bits mantissa |
complex | Shorthand for complex128. |
complex64 | Complex number, represented by two 32-bit floats (real and imaginary components) |
complex128 | Complex number, represented by two 64-bit floats (real and imaginary components) |
- shape: 数组维度,一般使用一个元组.
- dtype: 数据类型,例如
dtype=np.int32
(类型作为np的属性) - order: 多维数据储存方式显示,是使用’C’类型(行为主)还是’F’的fortran类型(列为主),’A’保留原类型.就是实际储存时的顺序按行(默认)还是按列.
- out: 用来储存输出结果.注意out的数组大小要合适.一般可选项.即使指明out也会有返回值.
- axis:
- copy:
numpy常用函数: np.func(..) :
产生数组
- array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0): 转换相应对象为数组.一般使用嵌套列表作为对象输入,元组也可以.
- zeros(shape, dtype=float64, order=’C’) : 产生0数组.shapre可以是数字(一维数字),也可以(3,4)这样多维数组.
- empty(shape, dtype=float, order=’C’) : 产生相应形状的未初始化数值的数组.速度快,但因由未知值而危险.
- ones(shape, dtype=float64, order=’C’) : 产生全是1的数组.
- zeros/empty/ones_like(a, dtype=None, order=’K’, subok=True): 根据输入数组a的形状产生相应的特殊数组.
- eye(shape, dtype=float64, order=’C’) : 产生对角是1其余是0的数组(单位阵).
- arange([start,] stop[, step,], dtype=None) : 产生序列化一维数组.和range类似.
- linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) : 在start和stop间平均地分成num份,返回一维数组.endpoint是否不含最后stop的点,retstep是否返回间隔.
- copy(array) : 深拷贝,复制一份新的. 也可以a.copy()来返回.
- vstack(a,b) : 两个数组合并成一个新的数组,垂直合并.深拷贝
- hstack(a,b) : 两个数组合并成一个新的数组,水平合并.深拷贝
- append(arr1,arr2,axis) :将arr2追加到arr1, 返回新数组.axis=0 按行追加,=1按列追加
数组数学运算(C写的底层,不能在数组对象作为方法使用!)
- reciprocal(x[, out]) 求倒数,返回逐个元素的倒数.
- add(x1, x2[, out=None]) 数组加法,逐个元素相加.数组大小最好一致,不一致的话小数组能数倍变为大数组才能逐一进行计算.
- negative(x[, out]) 逐个取反.
- subtract(x1, x2[, out]) 数组减法,逐个元素相加
- multiply(x1, x2[, out]) 数组点乘法,逐个元素相乘
- power(x1, x2[, out]) 第二个数组作为幂,逐个元素求幂.
- divide(x1, x2[, out]) 数组点除法,逐个元素相除.注意要是数组是整数和整数除返回整数.
- true_divide(x1, x2[, out]) 数组浮点点除法,逐个元素相除,必然返回浮点.
- floor_divide(x1, x2[, out]) 数组点除法,逐个元素相除,返回向下取整的整数/浮点.
- mod(x1, x2[, out]) 逐个元素求余.
- remainder(x1, x2[, out]) 逐个元素求余.和mod一样
- fmod(x1, x2[, out]) 逐个元素求余,但返回值符号跟x1一致.和matlab的rem函数等价。
- modf(x[, out1, out2]) 分隔元素和小数和整数部分,返回两个数组,第一个数组是小数部分的值,第二个是整数部分的值。符号跟元素一致
- sin(x[, out]) Trigonometric sine, element-wise.
- cos(x[, out]) Cosine element-wise.
- tan(x[, out]) Compute tangent element-wise.
- arcsin(x[, out]) Inverse sine, element-wise.
- arccos(x[, out]) Trigonometric inverse cosine, element-wise.
- arctan(x[, out]) Trigonometric inverse tangent, element-wise.
- hypot(x1, x2[, out]) Given the “legs” of a right triangle, return its hypotenuse.
- arctan2(x1, x2[, out]) Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
- degrees(x[, out]) Convert angles from radians to degrees.
- radians(x[, out]) Convert angles from degrees to radians.
- unwrap(p[, discont, axis]) Unwrap by changing deltas between values to 2*pi complement.
- deg2rad(x[, out]) Convert angles from degrees to radians.
- rad2deg(x[, out]) Convert angles from radians to degrees.
- sinh(x[, out]) Hyperbolic sine, element-wise.
- cosh(x[, out]) Hyperbolic cosine, element-wise.
- tanh(x[, out]) Compute hyperbolic tangent element-wise.
- arcsinh(x[, out]) Inverse hyperbolic sine element-wise.
- arccosh(x[, out]) Inverse hyperbolic cosine, element-wise.
- arctanh(x[, out]) Inverse hyperbolic tangent element-wise.
- around(a[, decimals, out]) Evenly round to the given number of decimals.
- round_(a[, decimals, out]) Round an array to the given number of decimals.注意末尾有
_
- rint(x[, out]) Round elements of the array to the nearest integer.
- fix(x[, y]) Round to nearest integer towards zero.
- floor(x[, out]) Return the floor of the input, element-wise.
- ceil(x[, out]) Return the ceiling of the input, element-wise.
- trunc(x[, out]) Return the truncated value of the input, element-wise.
- exp(x[, out]) Calculate the exponential of all elements in the input array.
- expm1(x[, out]) Calculate exp(x) - 1 for all elements in the array.
- exp2(x[, out]) Calculate 2**p for all p in the input array.
- log(x[, out]) Natural logarithm, element-wise.
- log10(x[, out]) Return the base 10 logarithm of the input array, element-wise.
- log2(x[, out]) Base-2 logarithm of x.
- log1p(x[, out]) Return the natural logarithm of one plus the input array, element-wise.
- logaddexp(x1, x2[, out]) Logarithm of the sum of exponentiations of the inputs.
- logaddexp2(x1, x2[, out]) Logarithm of the sum of exponentiations of the inputs in base-2.
- signbit(x[, out]) Returns element-wise True where signbit is set (less than zero).
- copysign(x1, x2[, out]) Change the sign of x1 to that of x2, element-wise.
- frexp(x[, out1, out2]) Decompose the elements of x into mantissa and twos exponent.
- ldexp(x1, x2[, out]) Returns x1 * 2**x2, element-wise.
- angle(z[, deg]) Return the angle of the complex argument.
- real(val) Return the real part of the elements of the array.
- imag(val) Return the imaginary part of the elements of the array.
- conj(x[, out]) Return the complex conjugate, element-wise.
- prod(a[, axis, dtype, out, keepdims]) Return the product of array elements over a given axis.(数组对象也有)
- sum(a[, axis, dtype, out, keepdims]) Sum of array elements over a given axis.(数组对象也有)
- nansum(a[, axis, dtype, out, keepdims]) Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
- cumprod(a[, axis, dtype, out]) Return the cumulative product of elements along a given axis.(数组对象也有)
- cumsum(a[, axis, dtype, out]) Return the cumulative sum of the elements along a given axis.(数组对象也有)
- diff(a[, n, axis]) Calculate the n-th order discrete difference along given axis.
- ediff1d(ary[, to_end, to_begin]) The differences between consecutive elements of an array.
- gradient(f, *varargs, **kwargs) Return the gradient of an N-dimensional array.
- cross(a, b[, axisa, axisb, axisc, axis]) Return the cross product of two (arrays of) vectors.
- trapz(y[, x, dx, axis]) Integrate along the given axis using the composite trapezoidal rule.
- i0(x) Modified Bessel function of the first kind, order 0.
- sinc(x) Return the sinc function.
- convolve(a, v[, mode]) Returns the discrete, linear convolution of two one-dimensional sequences.
- clip(a, a_min, a_max[, out]) Clip (limit) the values in an array.
- sqrt(x[, out]) Return the positive square-root of an array, element-wise.
- square(x[, out]) Return the element-wise square of the input.
- absolute(x[, out]) Calculate the absolute value element-wise.
- fabs(x[, out]) Compute the absolute values element-wise.
- sign(x[, out]) Returns an element-wise indication of the sign of a number.
- maximum(x1, x2[, out]) Element-wise maximum of array elements.
- minimum(x1, x2[, out]) Element-wise minimum of array elements.
- fmax(x1, x2[, out]) Element-wise maximum of array elements.
- fmin(x1, x2[, out]) Element-wise minimum of array elements.
- nan_to_num(x) Replace nan with zero and inf with finite numbers.
- real_if_close(a[, tol]) If complex input returns a real array if complex parts are close to zero.
- interp(x, xp, fp[, left, right]) One-dimensional linear interpolation.
选择数据
where, nonzero, choose
线性代数模块 np.linalg
Linear algebra basics:
- norm Vector or matrix norm
- inv Inverse of a square matrix(方阵求逆)
- solve Solve a linear system of equations
- det Determinant of a square matrix
- lstsq Solve linear least-squares problem
- pinv Pseudo-inverse (Moore-Penrose) calculated using a singular value decomposition
- matrix_power Integer power of a square matrix
Eigenvalues and decompositions:
- eig Eigenvalues and vectors of a square matrix
- eigh Eigenvalues and eigenvectors of a Hermitian matrix
- eigvals Eigenvalues of a square matrix
- eigvalsh Eigenvalues of a Hermitian matrix
- qr QR decomposition of a matrix
- svd Singular value decomposition of a matrix
- cholesky Cholesky decomposition of a matrix
Tensor operations:
- tensorsolve Solve a linear tensor equation
- tensorinv Calculate an inverse of a tensor
Matrix对象
矩阵是数组的一个小分支.必须是2维的,拥有数组所有特性,除了某些运算符重载了.另外,对于数组求和等归约运算可能改变维度(如sum,mean等),如变成(2,)甚至数值.但是对于矩阵会一直保持维度(2,1),(1,1),没有该问题. np.asmatrix和np.asarray可以方便转换(返回值只是原数据变换类型,因此数据其实是同样的数据). matrix对象方法参考.
- np.matrix(data, dtype=None, copy=True): 将数据转为矩阵,支持数组或者matlab形式字符串如”1,2,3;4,5,6”
- np.mat(data, dtype=None):和上类似,只是不复制.
- np.asmatrix(data, dtype=None):只是转换数据类型,数据还是那块数据.因此返回值改动会改变原数组.
- np.bmat(obj, ldict=None, gdict=None):使用字符串,嵌入列表或数组来构建数组.支持使用子数组名来调用子数组构建大数组.例如np.bmat(‘A,B; C,D’)(ABCD是四个小数组)
- M.A或getA(): 返回相应2维数组
- M.A1: 返回相应1维数组
- M.I: 矩阵求逆(相当于np.linalg.inv(M))
- M.T: 转置矩阵
- M.H: 共轭转置矩阵
- M*N: 矩阵相乘,相当于M.dot(N). (!!不同于数组每个元素相乘,和matlab一致!!)
- M**n: 方矩阵的乘幂.(!!不同于数组每个元素乘幂,相当于matlab的M^2!!)
- np.multiple(M,N): 矩阵的每个点乘.相当于数组的A*B,matlab的M.*N
以下函数在numpy.matlib
模块中,和一般的函数区别在于返回矩阵.
- empty(shape[, dtype, order]) 指定形状的矩阵,没初始化值.
- zeros(shape[, dtype, order]) 全0矩阵.
- ones(shape[, dtype, order]) 全1矩阵.
- eye(n[, M, k, dtype]) 返回n*M的矩阵,对角1其余0.k是对角线偏移值(大于0往上篇小于0往下偏)
- identity(n[, dtype]) 产生对角为1其余为0的方阵(类似于eye,但只能返回方阵)
- repmat(a, m, n) 重复某矩阵(0~2D) M*N次.
- rand(*args) 返回随机化[0,1)矩阵,参数可以是数个整数,也可以是维度元组.
- randn(*args) Return a random matrix with data from the “standard normal” distribution.
random模块 np.random.
rand(d1,d2…) : 返回相应维数[0,1)的随机数组 random((d1,d2…)) : 返回相应维数[0,1)的随机数组,和上面区别是使用形状的元组.
文件数据输入输出
a.tofile(fid, sep=””, format=”%s”) Write array to a file as text or binary (default)
SciPy交互
- Vectorize函数
def t(x):
return x + 3
a1 = scipy.zeros((5,4))
a1
NumPy array, format: long
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
s = scipy.vectorize(t)
a2 = s(a1)
a2
NumPy array, format: long
[[3 3 3 3]
[3 3 3 3]
[3 3 3 3]
[3 3 3 3]
[3 3 3 3]]
- NumPy和SciPy相互转化
import numpy
import scipy
a1 = zeros((4,6))
type(a1)
<type 'scipy.ndarray'>
a2 = numpy.asarray(a1)
type(a2)
<type 'numpy.ndarray'>
a3 = numpy.zeros((3,5))
type(a3)
<type 'numpy.ndarray'>
a4 = scipy.asarray(a3)
type(a4)
<type 'scipy.ndarray'>