numpy 学习3

来源:互联网 发布:漫威电影补剧顺序 知乎 编辑:程序博客网 时间:2024/06/05 05:25

复习:

1、生成随机的正太分布N(3, 6.25)?怎么写?

>>a=2.5*np.random.randn(2,4)+3

array([[ 2.56193501,  2.35561233,  2.33461718,  7.16164167],
           [ 4.31703616,  3.95864108,  0.26704414,  3.86756291]])


2、计算这组数据中的最大值

print a.max()


3、对一组数据进行快速排序

np.sort(a,kind='quicksort')

搬一组原始例子:

>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),...           ('Galahad', 1.7, 38)]>>> a = np.array(values, dtype=dtype)       # create a structured array>>> np.sort(a, order='height')                        array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),       ('Lancelot', 1.8999999999999999, 38)],      dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
看的懂吗?努力去看懂


4、计算平均值:去官方文档上去找。

>>a.mean()


5、计算E(x) : 

>>print var(a)


学习:

a.ravel() 
# returns the array, flattened 
变成一维矩阵

a.T  # returns the array, transposed         逆矩阵
np.vstack((a,b))                             竖直链接
np.hstack((a,b))                             水平连接
>>> a = np.array((1,2,3))>>> b = np.array((2,3,4))>>> np.column_stack((a,b))array([[1, 2],       [2, 3],       [3, 4]])                             a与b之间的连接

array([[ 9.,  5.,  6.,  3.,|  6.,  8.,  0.,  7.,|  9.,  7.,  2.,  7.],       [ 1.,  4.,  9.,  2.,|  2.,  1.,  0.,  6.,|  2.,  2.,  4.,  0.]])>>> np.hsplit(a,3)                          # 分割,看我上面的红线,这样分割[array([[ 9.,  5.,  6.,  3.],       [ 1.,  4.,  9.,  2.]]), array([[ 6.,  8.,  0.,  7.],       [ 2.,  1.,  0.,  6.]]), array([[ 9.,  7.,  2.,  7.],       [ 2.,  2.,  4.,  0.]])]>>> np.hsplit(a,(3,4))                      # Split a after the third and the fourth column #意思是在第三列和第四列分割[array([[ 9.,  5.,  6.],       [ 1.,  4.,  9.]]), array([[ 3.],       [ 2.]]), array([[ 6.,  8.,  0.,  7.,  9.,  7.,  2.,  7.],       [ 2.,  1.,  0.,  6.,  2.,  2.,  4.,  0.]])]
那么横着分割怎么分割?应该是vsplite吧。v是行,h是列,matplotlib中好像大多都是这样


以下方法掌握了多少?

Array Creation
arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones,ones_like, r, zeros, zeros_like
Conversions
ndarray.astype, atleast_1d, atleast_2d, atleast_3d, mat
Manipulations
array_split, column_stackconcatenatediagonaldsplit, dstack, hsplit, hstackndarray.itemnewaxisravelrepeat,reshape, resizesqueezeswapaxestaketransposevsplit, vstack      #stack是拼接,split是剪切  dsplit=hsplit 是列切 ,vsplit是行切 
Questions
all, any, nonzero, where
Ordering
argmax, argmin, argsort, max, min, ptp, searchsorted, sort
Operations
choose, compress, cumprod, cumsum, inner, ndarray.fill, imag, prod, put, putmask, real, sum
Basic Statistics
cov, mean, std, var
Basic Linear Algebra
cross, dot, outer, linalg.svd, vdot

举例学习:

1、numpy.geomspace

Parameters:

start : scalar  #scale是比例的意思

The starting value of the sequence.

stop : scalar

The final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

num : integer, optional

Number of samples to generate. Default is 50.

endpoint : boolean, optional

If true, stop is the last sample. Otherwise, it is not included. Default is True.

dtype : dtype

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

例子:看了例子不可能不知道是什么意思,geom是几何的意思,space是空格,几何倍数的空格再清楚不过。
>>> np.geomspace(1, 1000, num=4)array([    1.,    10.,   100.,  1000.])>>> np.geomspace(1, 1000, num=3, endpoint=False)array([   1.,   10.,  100.])>>> np.geomspace(1, 1000, num=4, endpoint=False)array([   1.        ,    5.62341325,   31.6227766 ,  177.827941  ])>>> np.geomspace(1, 256, num=9)array([   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.,  256.])

2、numpy.meshgrid 网格

Parameters:

x1, x2,..., xn : array_like

1-D arrays representing the coordinates of a grid.

indexing : {‘xy’, ‘ij’}, optional

Cartesian (‘xy’, default) or matrix (‘ij’) indexing of output. See Notes for more details.

New in version 1.7.0.

sparse : bool, optional

If True a sparse grid is returned in order to conserve memory. Default is False.

New in version 1.7.0.

copy : bool, optional

If False, a view into the original arrays are returned in order to conserve memory. Default is True. Please note that sparse=False, copy=False will likely return non-contiguous arrays. Furthermore, more than one element of a broadcast array may refer to a single memory location. If you need to write to the arrays, make copies first.

New in version 1.7.0.

Returns:

X1, X2,..., XN : ndarray

For vectors x1x2,..., ‘xn’ with lengths Ni=len(xi) , return (N1, N2, N3,...Nn) shaped arrays if indexing=’ij’ or (N2, N1, N3,...Nn) shaped arrays if indexing=’xy’ with the elements of xirepeated to fill the matrix along the first dimension for x1, the second for x2 and so on.

文档应该能看懂了!
参数:(多个向量 --必选参数--,索引 --可选--,sparse ---可选 意思我不懂,不过他写着类型是true或者false,如果选择True就节约内存---,copy ----)
返回值:返回向量x1,x2,x3.....那么返回的这个向量具有什么特点呢,这个向量的形式要使这些成为参数的这些向量形式一致。
>>> nx, ny = (3, 2)>>> x = np.linspace(0, 1, nx)>>> y = np.linspace(0, 1, ny)>>> xv, yv = meshgrid(x, y)>>> xvarray([[ 0. ,  0.5,  1. ],       [ 0. ,  0.5,  1. ]])>>> yvarray([[ 0.,  0.,  0.],       [ 1.,  1.,  1.]])>>> xv, yv = meshgrid(x, y, sparse=True)  # make sparse output arrays>>> xvarray([[ 0. ,  0.5,  1. ]])>>> yvarray([[ 0.],       [ 1.]])