本文翻译自:这里,并会添加笔(译)者的一些适当的注解。
1.导入numpy,并重命名为np(★☆☆)
import numpy as np2.输出numpy的版本和配置(★☆☆)
PRint(np.__version__)np.show_config()3.创建大小为10的空向量(★☆☆)
Z = np.zeros(10)print(Z)4.如何查找数组的内存大小(★☆☆)
Z = np.zeros((10,10))print("%d bytes" % (Z.size * Z.itemsize))5.如何从命令行获取numpy中add函数的文档?(★☆☆)
%run `python -c "import numpy; numpy.info(numpy.add)"`#这个问题貌似有点偏,这里给出笔者的实例输出:C:/WINDOWS/system32>python -c "import numpy; numpy.info(numpy.add)"add(x1, x2[, out])Add arguments element-wise.Parameters----------x1, x2 : array_like The arrays to be added. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which may be the shape of one or the other).Returns-------add : ndarray or scalar The sum of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars.Notes-----Equivalent to `x1` + `x2` in terms of array broadcasting.Examples-------->>> np.add(1.0, 4.0)5.0>>> x1 = np.arange(9.0).reshape((3, 3))>>> x2 = np.arange(3.0)>>> np.add(x1, x2)array([[ 0., 2., 4.], [ 3., 5., 7.], [ 6., 8., 10.]])当然也可以在python环境下得到,输入:
np.info(np.add)6.创建一个大小为10的空向量,但是第五个值为1
Z = np.zeros(10)Z[4] = 1print(Z)7.创建一个值为10到49的向量(★☆☆)
Z = np.arange(10,50)print(Z)8.反转向量(第一个元素变为最后一个元素)(★☆☆)
Z = np.arange(50)Z = Z[::-1]print(Z)9.创建一个值为0到8的3x3矩阵(★☆☆)
Z = np.arange(9).reshape(3,3)print(Z)10.从[1,2,0,0,4,0]中查找非零元素的下标(★☆☆)
nz = np.nonzero([1,2,0,0,4,0])print(nz)11.创建3x3单位矩阵(★☆☆)
Z = np.eye(3)print(Z)12.创建一个由随机数组成的3x3x3数组(★☆☆)
Z = np.random.random((3,3,3))print(Z)13.创建一个由随机数组成的10x10数组,并找到最小值和最大值(★☆☆)
Z = np.random.random((10,10))Zmin, Zmax = Z.min(), Z.max()print(Zmin, Zmax)14.创建一个大小为30的随机向量,并找到平均值(★☆☆)
Z = np.random.random(30)m = Z.mean()print(m)15.创建一个二维数组,其边框上均为1,内部均为0(★☆☆)
Z = np.ones((10,10))Z[1:-1,1:-1] = 0print(Z)16.如何在现有数组周围添加边框(用0填充)?(★☆☆)
Z = np.ones((5,5))Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)print(Z)17.下列表达式的输出值是什么?(★☆☆)
print(0 * np.nan)print(np.nan == np.nan)print(np.inf > np.nan)print(np.nan - np.nan)print(0.3 == 3 * 0.1)18.创建一个5x5矩阵,值为1,2,3,4的元素刚好在对角线下方(★☆☆)
Z = np.diag(1+np.arange(4),k=-1)print(Z)19.创建一个8x8矩阵,并将其填充为一个棋盘图案(★☆☆)
Z = np.zeros((8,8),dtype=int)Z[1::2,::2] = 1Z[::2,1::2] = 1print(Z)20.考虑一个(6,7,8)的数组,第100个元素的索引(x,y,z)是什么?(★☆☆)
print(np.unravel_index(100,(6,7,8)))21.使用tile函数创建8*8棋盘矩阵(★☆☆)
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))print(Z)22.将5*5随机矩阵归一化(★☆☆)
Z = np.random.random((5,5))Zmax, Zmin = Z.max(), Z.min()Z = (Z - Zmin)/(Zmax - Zmin)print(Z)23.创建将颜色描述为四个无符号字节(RGBA)的自定义dtype(★☆☆)
color = np.dtype([("r", np.ubyte, 1), ("g", np.ubyte, 1), ("b", np.ubyte, 1), ("a", np.ubyte, 1)])24.将5x3矩阵乘以3x2矩阵(实矩阵乘积)(★☆☆)
Z = np.dot(np.ones((5,3)), np.ones((3,2)))print(Z)# Alternative solution, in Python 3.5 and aboveZ = np.ones((5,3)) @ np.ones((3,2))print(Z)25.给定一个1维数组,取反在3和8之间的所有元素(★☆☆)
Z = np.arange(11)Z[(3 < Z) & (Z <= 8)] *= -1print(Z)26.What is the output of the following script? (★☆☆)
# Author: Jake VanderPlasprint(sum(range(5),-1))from numpy import *print(sum(range(5),-1))#笔者注:这段代码的输出很有意思,下面给出笔者的测试例子:>>> from numpy import *>>> for i in range(5):... print(i)... print(sum(range(i),-1))... print(sum(range(i)))...00.00.0100211333466>>>27.考虑一个整数向量Z,下面那些表达式是合法的? (★☆☆)
Z**Z2 << Z >> 2Z <- Z1j*ZZ/1/1Z<Z>Z28.下列表达式的结果是什么?(★☆☆)
print(np.array(0) / np.array(0))print(np.array(0) // np.array(0))print(np.array([np.nan]).astype(int).astype(float))笔者注:/ 代表浮点数除法的,得到的结果是浮点数;// 是整数除法,得到的结果是整数。
29.如何从零舍入浮点数组?(★☆☆)
# Author: Charles R HarrisZ = np.random.uniform(-10,+10,10)print (np.copysign(np.ceil(np.abs(Z)), Z))笔者注:copysign 和 ceil函数的使用方法:
#copysign:copysign(x1, x2[, out])Change the sign of x1 to that of x2, element-wise.If both arguments are arrays or sequences, they have to be of the samelength. If `x2` is a scalar, its sign will be copied to all elements of`x1`.Parameters----------x1 : array_like Values to change the sign of.x2 : array_like The sign of `x2` is copied to `x1`.out : ndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. See doc.ufuncs.Returns-------out : array_like The values of `x1` with the sign of `x2`.Examples-------->>> np.copysign(1.3, -1)-1.3>>> 1/np.copysign(0, 1)inf>>> 1/np.copysign(0, -1)-inf>>> np.copysign([-1, 0, 1], -1.1)array([-1., -0., -1.])>>> np.copysign([-1, 0, 1], np.arange(3)-1)array([-1., 0., 1.])#------------------------------------------------------#ceil:ceil(x[, out])Return the ceiling of the input, element-wise.The ceil of the scalar `x` is the smallest integer `i`, such that`i >= x`. It is often denoted as :math:`/lceil x /rceil`.Parameters----------x : array_like Input data.Returns-------y : ndarray or scalar The ceiling of each element in `x`, with `float` dtype.See Also--------floor, trunc, rintExamples-------->>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])>>> np.ceil(a)array([-1., -1., -0., 1., 2., 2., 2.])30.如何找出两个数组的公共元素? (★☆☆)
Z1 = np.random.randint(0,10,10)Z2 = np.random.randint(0,10,10)print(np.intersect1d(Z1,Z2))笔者注:关于intersect1d函数的使用:
intersect1d(ar1, ar2, assume_unique=False)Find the intersection of two arrays.Return the sorted, unique values that are in both of the input arrays.Parameters----------ar1, ar2 : array_like Input arrays.assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.Returns-------intersect1d : ndarray Sorted 1D array of common and unique elements.See Also--------numpy.lib.arraysetops : Module with a number of other functions for performing set Operations on arrays.Examples-------->>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])array([1, 3])To intersect more than two arrays, use functools.reduce:>>> from functools import reduce>>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))array([3])31.如何忽略所有numpy的警告(warning)信息(不推荐)? (★☆☆)
# Suicide mode ondefaults = np.seterr(all="ignore")Z = np.ones(1) / 0# Back to sanity_ = np.seterr(**defaults)一个等价的方式,用一个上下文管理器(context manager):
with np.errstate(divide='ignore'): Z = np.ones(1) / 032.下列表达式是正确的(true)吗? (★☆☆)
np.sqrt(-1) == np.emath.sqrt(-1)33.如何获得昨天,今天和明天的日期?(★☆☆)
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')today = np.datetime64('today', 'D')tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')34.如何获得所有与2016年7月相对应的日期?
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')print(Z)35.如何计算 ((A+B)*(-A/2))到位(没有副本)? (★★☆)
A = np.ones(3)*1B = np.ones(3)*2C = np.ones(3)*3np.add(A,B,out=B)np.divide(A,2,out=A)np.negative(A,out=A)np.multiply(A,B,out=A)36.使用5种不同的方法提取随机数组的整数部分(★★☆)
Z = np.random.uniform(0,10,10)print (Z - Z%1)print (np.floor(Z))print (np.ceil(Z)-1)print (Z.astype(int))print (np.trunc(Z))笔者注:trunc函数的使用方法:
trunc(x[, out])Return the truncated value of the input, element-wise.The truncated value of the scalar `x` is the nearest integer `i` whichis closer to zero than `x` is. In short, the fractional part of thesigned number `x` is discarded.Parameters----------x : array_like Input data.Returns-------y : ndarray or scalar The truncated value of each element in `x`.See Also--------ceil, floor, rintNotes-----.. versionadded:: 1.3.0Examples-------->>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])>>> np.trunc(a)array([-1., -1., -0., 0., 1., 1., 2.])37.创建一个5x5矩阵,每一行的值范围为从0到4(★★☆)
Z = np.zeros((5,5))Z += np.arange(5)print(Z)38.考虑一个可生成10个整数的生成函数,并使用它来构建一个数组(★☆☆)
def generate(): for x in range(10): yield xZ = np.fromiter(generate(),dtype=float,count=-1)print(Z)笔者注:fromiter函数的使用方法:
fromiter(iterable, dtype, count=-1)Create a new 1-dimensional array from an iterable object.Parameters----------iterable : iterable object An iterable object providing data for the array.dtype : data-type The data-type of the returned array.count : int, optional The number of items to read from *iterable*. The default is -1, which means all data is read.Returns-------out : ndarray The output array.Notes-----Specify `count` to improve performance. It allows ``fromiter`` topre-allocate the output array, instead of resizing it on demand.Examples-------->>> iterable = (x*x for x in range(5))>>> np.fromiter(iterable, np.float)array([ 0., 1., 4., 9., 16.])39.创建一个大小为10的向量,其值范围从0到1,但都不包括0和1(★★☆)
Z = np.linspace(0,1,12,endpoint=True)[1:-1]print(Z)笔者注:linspace函数的使用方法:
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)Return evenly spaced numbers over a specified interval.Returns `num` evenly spaced samples, calculated over theinterval [`start`, `stop`].The endpoint of the interval can optionally be excluded.Parameters----------start : scalar The starting value of the sequence.stop : scalar The end value of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced samples, so that `stop` is excluded. Note that the step size changes when `endpoint` is False.num : int, optional Number of samples to generate. Default is 50. Must be non-negative.endpoint : bool, optional If True, `stop` is the last sample. Otherwise, it is not included. Default is True.retstep : bool, optional If True, return (`samples`, `step`), where `step` is the spacing between samples.dtype : dtype, optional The type of the output array. If `dtype` is not given, infer the data type from the other input arguments. .. versionadded:: 1.9.0Returns-------samples : ndarray There are `num` equally spaced samples in the closed interval ``[start, stop]`` or the half-open interval ``[start, stop)`` (depending on whether `endpoint` is True or False).step : float Only returned if `retstep` is True Size of spacing between samples.See Also--------arange : Similar to `linspace`, but uses a step size (instead of the number of samples).logspace : Samples uniformly distributed in log space.Examples-------->>> np.linspace(2.0, 3.0, num=5) array([ 2. , 2.25, 2.5 , 2.75, 3. ])>>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([ 2. , 2.2, 2.4, 2.6, 2.8])>>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)Graphical illustration:>>> import matplotlib.pyplot as plt>>> N = 8>>> y = np.zeros(N)>>> x1 = np.linspace(0, 10, N, endpoint=True)>>> x2 = np.linspace(0, 10, N, endpoint=False)>>> plt.plot(x1, y, 'o')[<matplotlib.lines.Line2D object at 0x...>]>>> plt.plot(x2, y + 0.5, 'o')[<matplotlib.lines.Line2D object at 0x...>]>>> plt.ylim([-0.5, 1])(-0.5, 1)>>> plt.show()40.创建一个大小为10的随机向量并对其排序(★★☆)
Z = np.random.random(10)Z.sort()print(Z)41.如何对一个小数组求和使得比使用np.sum更快?
# Author: Evgeni BurovskiZ = np.arange(10)np.add.reduce(Z)笔者注:reduce函数在numpy.add模块中实现,其可被称为一个ufunc函数(ufunc是universal function的缩写,它是一种能对数组的每个元素进行操作的函数。NumPy内置的许多ufunc函数都是在C语言级别实现的,因此它们的计算速度非常快),因此比np.sum计算得更快(后者貌似是用python实现的?)
而若想计算Z中所有元素的乘积,可用:
np.multiply.reduce(Z)42.考虑两个随机数组A和B,检查它们是否相等(★★☆)
A = np.random.randint(0,2,5)B = np.random.randint(0,2,5)# 假设array的形状(shape)相同和一个误差容限(tolerance)equal = np.allclose(A,B)print(equal)# 检查形状和元素值,没有误差容限(值必须完全相等)equal = np.array_equal(A,B)print(equal)笔者注:allclose函数的使用方法:
allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)Returns True if two arrays are element-wise equal within a tolerance.The tolerance values are positive, typically very small numbers. Therelative difference (`rtol` * abs(`b`)) and the absolute difference`atol` are added together to compare against the absolute differencebetween `a` and `b`.If either array contains one or more NaNs, False is returned.Infs are treated as equal if they are in the same place and of the samesign in both arrays.Parameters----------a, b : array_like Input arrays to compare.rtol : float The relative tolerance parameter (see Notes).atol : float The absolute tolerance parameter (see Notes).equal_nan : bool Whether to compare NaN's as equal. If True, NaN's in `a` will be considered equal to NaN's in `b` in the output array. .. versionadded:: 1.10.0Returns-------allclose : bool Returns True if the two arrays are equal within the given tolerance; False otherwise.See Also--------isclose, all, anyNotes-----If the following equation is element-wise True, then allclose returnsTrue. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))The above equation is not symmetric in `a` and `b`, so that`allclose(a, b)` might be different from `allclose(b, a)` insome rare cases.Examples-------->>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])False>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])True>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])False>>> np.allclose([1.0, np.nan], [1.0, np.nan])False>>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)True43.使数组不可变(只读)(★★☆)
Z = np.zeros(10)Z.flags.writeable = FalseZ[0] = 144.考虑一个笛卡尔坐标下的随机10x2矩阵,将它们转换为极坐标(★★☆)
Z = np.random.random((10,2))X,Y = Z[:,0], Z[:,1]R = np.sqrt(X**2+Y**2)T = np.arctan2(Y,X)print(R)print(T)45.创建大小为10的随机向量,并将最大值替换为0(★★☆)
Z = np.random.random(10)Z[Z.argmax()] = 0print(Z)46.创建一个结构化数组,其中x和y坐标覆盖 [0,1]x[0,1] 区域(★★☆)
Z = np.zeros((5,5), [('x',float),('y',float)])Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5), np.linspace(0,1,5))print(Z)笔者注:meshgrid函数的用法
meshgrid(*xi, **kwargs)Return coordinate matrices from coordinate vectors.Make N-D coordinate arrays for vectorized evaluations ofN-D scalar/vector fields over N-D grids, givenone-dimensional coordinate arrays x1, x2,..., xn... versionchanged:: 1.9 1-D and 0-D cases are allowed.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. .. versionadded:: 1.7.0sparse : bool, optional If True a sparse grid is returned in order to conserve memory. Default is False. .. versionadded:: 1.7.0copy : 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. .. versionadded:: 1.7.0Returns-------X1, X2,..., XN : ndarray For vectors `x1`, `x2`,..., '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 `xi` repeated to fill the matrix along the first dimension for `x1`, the second for `x2` and so on.Notes-----This function supports both indexing conventions through the indexingkeyWord argument. Giving the string 'ij' returns a meshgrid withmatrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.In the 2-D case with inputs of length M and N, the outputs are of shape(N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D casewith inputs of length M, N and P, outputs are of shape (N, M, P) for'xy' indexing and (M, N, P) for 'ij' indexing. The difference isillustrated by the following code snippet:: xv, yv = meshgrid(x, y, sparse=False, indexing='ij') for i in range(nx): for j in range(ny): # treat xv[i,j], yv[i,j] xv, yv = meshgrid(x, y, sparse=False, indexing='xy') for i in range(nx): for j in range(ny): # treat xv[j,i], yv[j,i]In the 1-D and 0-D case, the indexing and sparse keywords have no effect.See Also--------index_tricks.mgrid : Construct a multi-dimensional "meshgrid" using indexing notation.index_tricks.ogrid : Construct an open multi-dimensional "meshgrid" using indexing notation.Examples-------->>> 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.]])`meshgrid` is very useful to evaluate functions on a grid.>>> x = np.arange(-5, 5, 0.1)>>> y = np.arange(-5, 5, 0.1)>>> xx, yy = meshgrid(x, y, sparse=True)>>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)>>> h = plt.contourf(x,y,z)47.给定两个array X和Y,构造柯西(Cauchy)矩阵C (Cij =1/(xi - yj))
# Author: Evgeni BurovskiX = np.arange(8)Y = X + 0.5C = 1.0 / np.subtract.outer(X, Y)print(np.linalg.det(C))笔者注:outer函数的用法
outer(A, B)Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of``op.outer(A, B)`` is an array of dimension M + N such that:.. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])For `A` and `B` one-dimensional, this is equivalent to:: r = empty(len(A),len(B)) for i in range(len(A)): for j in range(len(B)): r[i,j] = op(A[i], B[j]) # op = ufunc in questionParameters----------A : array_like First arrayB : array_like Second arrayReturns-------r : ndarray Output arraySee Also--------numpy.outerExamples-------->>> np.multiply.outer([1, 2, 3], [4, 5, 6])array([[ 4, 5, 6], [ 8, 10, 12], [12, 15, 18]])A multi-dimensional example:>>> A = np.array([[1, 2, 3], [4, 5, 6]])>>> A.shape(2, 3)>>> B = np.array([[1, 2, 3, 4]])>>> B.shape(1, 4)>>> C = np.multiply.outer(A, B)>>> C.shape; C(2, 3, 1, 4)array([[[[ 1, 2, 3, 4]], [[ 2, 4, 6, 8]], [[ 3, 6, 9, 12]]], [[[ 4, 8, 12, 16]], [[ 5, 10, 15, 20]], [[ 6, 12, 18, 24]]]])48.打印每个numpy标量类型的最小和最大可表示值(★★☆)
for dtype in [np.int8, np.int32, np.int64]: print(np.iinfo(dtype).min) print(np.iinfo(dtype).max)for dtype in [np.float32, np.float64]: print(np.finfo(dtype).min) print(np.finfo(dtype).max) print(np.finfo(dtype).eps)49.如何打印数组的所有值? (★★☆)
np.set_printoptions(threshold=np.nan)Z = np.zeros((16,16))print(Z)笔者注:如果一个数组用来打印太大了,NumPy会自动省略中间部分而只打印角落。比如:
>>> print arange(10000)[ 0 1 2 ..., 9997 9998 9999]禁用NumPy的这种行为并强制打印整个数组,我们可以通过设置printoptions参数来更改打印选项。
50.如何在数组中找到最接近的值(给定标量)? (★★☆)
Z = np.arange(100)v = np.random.uniform(0,100)index = (np.abs(Z-v)).argmin()print(Z[index])笔者注:argmin函数的用法:
argmin(a, axis=None, out=None)Returns the indices of the minimum values along an axis.Parameters----------a : array_like Input array.axis : int, optional By default, the index is into the flattened array, otherwise along the specified axis.out : array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.Returns-------index_array : ndarray of ints Array of indices into the array. It has the same shape as `a.shape` with the dimension along `axis` removed.See Also--------ndarray.argmin, argmaxamin : The minimum value along a given axis.unravel_index : Convert a flat index into an index tuple.Notes-----In case of multiple occurrences of the minimum values, the indicescorresponding to the first occurrence are returned.Examples-------->>> a = np.arange(6).reshape(2,3)>>> aarray([[0, 1, 2], [3, 4, 5]])>>> np.argmin(a)0>>> np.argmin(a, axis=0)array([0, 0, 0])>>> np.argmin(a, axis=1)array([0, 0])>>> b = np.arange(6)>>> b[4] = 0>>> barray([0, 1, 2, 3, 0, 5])>>> np.argmin(b) # Only the first occurrence is returned.051.创建表示位置(x,y)和颜色(r,g,b)的结构化数组(★★☆)
Z = np.zeros(10, [ ('position', [ ('x', float, 1), ('y', float, 1)]), ('color', [ ('r', float, 1), ('g', float, 1), ('b', float, 1)])])print(Z)52.考虑表示坐标的形状为(100,2)的随机向量,找到点与点的距离(★★☆)
Z = np.random.random((10,2))X,Y = np.atleast_2d(Z[:,0], Z[:,1])D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)print(D)#--------------------------------------# 使用scipy更快import scipy.spatialZ = np.random.random((10,2))D = scipy.spatial.distance.cdist(Z,Z)print(D)笔者注:atleast_2d函数的使用方法:
atleast_2d(*arys)View inputs as arrays with at least two dimensions.Parameters----------arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.Returns-------res, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 2``. Copies are avoided where possible, and views with two or more dimensions are returned.See Also--------atleast_1d, atleast_3dExamples-------->>> np.atleast_2d(3.0)array([[ 3.]])>>> x = np.arange(3.0)>>> np.atleast_2d(x)array([[ 0., 1., 2.]])>>> np.atleast_2d(x).base is xTrue>>> np.atleast_2d(1, [1, 2], [[1, 2]])[array([[1]]), array([[1, 2]]), array([[1, 2]])]53.如何将float(32位)数组转换为整数(32位)?
Z = np.arange(10, dtype=np.int32)Z = Z.astype(np.float32, copy=False)print(Z)笔者注:astype函数的用法
a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)Copy of the array, cast to a specified type.Parameters----------dtype : str or dtype Typecode or data-type to which the array is cast.order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout order of the result. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. Default is 'K'.casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Defaults to 'unsafe' for backwards compatibility. * 'no' means the data types should not be cast at all. * 'equiv' means only byte-order changes are allowed. * 'safe' means only casts which can preserve values are allowed. * 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done.subok : bool, optional If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.copy : bool, optional By default, astype always returns a newly allocated array. If this is set to false, and the `dtype`, `order`, and `subok` requirements are satisfied, the input array is returned instead of a copy.Returns-------arr_t : ndarray Unless `copy` is False and the other conditions for returning the input array are satisfied (see description for `copy` input parameter), `arr_t` is a new array of the same shape as the input array, with dtype, order given by `dtype`, `order`.Notes-----Starting in NumPy 1.9, astype method now returns an error if the stringdtype to cast to is not long enough in 'safe' casting mode to hold the maxvalue of integer/float array that is being casted. Previously the castingwas allowed even if the result was truncated.Raises------ComplexWarning When casting from complex to float or int. To avoid this, one should use ``a.real.astype(t)``.Examples-------->>> x = np.array([1, 2, 2.5])>>> xarray([ 1. , 2. , 2.5])>>> x.astype(int)array([1, 2, 2])54.如何读取以下文件? (★★☆)
from io import StringIO# 假文件s = StringIO("""1, 2, 3, 4, 5/n 6, , , 7, 8/n , , 9,10,11/n""")Z = np.genfromtxt(s, delimiter=",", dtype=np.int)print(Z)笔者注:genfromtxt函数的用法:
genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None)Load data from a text file, with missing values handled as specified.Each line past the first `skip_header` lines is split at the `delimiter`character, and characters following the `comments` character are discarded.Parameters----------fname : file, str, list of str, generator File, filename, list, or generator to read. If the filename extension is `.gz` or `.bz2`, the file is first decompressed. Mote that generators must return byte strings in Python 3k. The strings in a list or produced by a generator are treated as lines.dtype : dtype, optional Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually.comments : str, optional The character used to indicate the start of a comment. All the characters occurring on a line after a comment are discardeddelimiter : str, int, or sequence, optional The string used to separate values. By default, any consecutive whitespaces act as delimiter. An integer or sequence of integers can also be provided as width(s) of each field.skiprows : int, optional `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.skip_header : int, optional The number of lines to skip at the beginning of the file.skip_footer : int, optional The number of lines to skip at the end of the file.converters : variable, optional The set of functions that convert the data of a column to a value. The converters can also be used to provide a default value for missing data: ``converters = {3: lambda s: float(s or 0)}``.missing : variable, optional `missing` was removed in numpy 1.10. Please use `missing_values` instead.missing_values : variable, optional The set of strings corresponding to missing data.filling_values : variable, optional The set of values to be used as default when the data are missing.usecols : sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.names : {None, True, str, sequence}, optional If `names` is True, the field names are read from the first valid line after the first `skip_header` lines. If `names` is a sequence or a single-string of comma-separated names, the names will be used to define the field names in a structured dtype. If `names` is None, the names of the dtype fields will be used, if any.excludelist : sequence, optional A list of names to exclude. This list is appended to the default list ['return','file','print']. Excluded names are appended an underscore: for example, `file` would become `file_`.deletechars : str, optional A string combining invalid characters that must be deleted from the names.defaultfmt : str, optional A format used to define default field names, such as "f%i" or "f_%02i".autostrip : bool, optional Whether to automatically strip white spaces from the variables.replace_space : char, optional Character(s) used in replacement of white spaces in the variables names. By default, use a '_'.case_sensitive : {True, False, 'upper', 'lower'}, optional If True, field names are case sensitive. If False or 'upper', field names are converted to upper case. If 'lower', field names are converted to lower case.unpack : bool, optional If True, the returned array is transposed, so that arguments may be unpacked using ``x, y, z = loadtxt(...)``usemask : bool, optional If True, return a masked array. If False, return a regular array.loose : bool, optional If True, do not raise errors for invalid values.invalid_raise : bool, optional If True, an exception is raised if an inconsistency is detected in the number of columns. If False, a warning is emitted and the offending lines are skipped.max_rows : int, optional The maximum number of rows to read. Must not be used with skip_footer at the same time. If given, the value must be at least 1. Default is to read the entire file. .. versionadded:: 1.10.0Returns-------out : ndarray Data read from the text file. If `usemask` is True, this is a masked array.See Also--------numpy.loadtxt : equivalent function when no data is missing.Notes-----* When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any missing data between two fields.* When the variables are named (either by a flexible dtype or with `names`, there must not be any header in the file (else a ValueError exception is raised).* Individual values are not stripped of spaces by default. When using a custom converter, make sure the function does remove spaces.References----------.. [1] Numpy User Guide, section `I/O with Numpy <http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.Examples--------->>> from io import StringIO>>> import numpy as npComma delimited file with mixed dtype>>> s = StringIO("1,1.3,abcde")>>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),... ('mystring','S5')], delimiter=",")>>> dataarray((1, 1.3, 'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])Using dtype = None>>> s.seek(0) # needed for StringIO example only>>> data = np.genfromtxt(s, dtype=None,... names = ['myint','myfloat','mystring'], delimiter=",")>>> dataarray((1, 1.3, 'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])Specifying dtype and names>>> s.seek(0)>>> data = np.genfromtxt(s, dtype="i8,f8,S5",... names=['myint','myfloat','mystring'], delimiter=",")>>> dataarray((1, 1.3, 'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])An example with fixed-width columns>>> s = StringIO("11.3abcde")>>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],... delimiter=[1,3,5])>>> dataarray((1, 1.3, 'abcde'), dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')])55.numpy数组的枚举(enumerate )的等价操作是什么? (★★☆)
Z = np.arange(9).reshape(3,3)for index, value in np.ndenumerate(Z): print(index, value)for index in np.ndindex(Z.shape): print(index, Z[index])笔者注:ndenumerate函数的用法:
Multidimensional index iterator.Return an iterator yielding pairs of array coordinates and values.Parameters----------arr : ndarray Input array.See Also--------ndindex, flatiterExamples-------->>> a = np.array([[1, 2], [3, 4]])>>> for index, x in np.ndenumerate(a):... print(index, x)(0, 0) 1(0, 1) 2(1, 0) 3(1, 1) 4Methods: next -- Standard iterator method, returns the index tuple and array value.56.生成一个通用的二维高斯状( Gaussian-like )数组(★★☆)
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))D = np.sqrt(X*X+Y*Y)sigma, mu = 1.0, 0.0G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )print(G)57.如何在二维数组中随机放置p个元素? (★★☆)
# Author: Divakarn = 10p = 3Z = np.zeros((n,n))np.put(Z, np.random.choice(range(n*n), p, replace=False),1)print(Z)笔者注:put和choice函数使用方法如下:
put(a, ind, v, mode='raise')Replaces specified elements of an array with given values.The indexing works on the flattened target array. `put` is roughlyequivalent to::: a.flat[ind] = vParameters----------a : ndarray Target array.ind : array_like Target indices, interpreted as integers.v : array_like Values to place in `a` at target indices. If `v` is shorter than `ind` it will be repeated as necessary.mode : {'raise', 'wrap', 'clip'}, optional Specifies how out-of-bounds indices will behave. * 'raise' -- raise an error (default) * 'wrap' -- wrap around * 'clip' -- clip to the range 'clip' mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.See Also--------putmask, placeExamples-------->>> a = np.arange(5)>>> np.put(a, [0, 2], [-44, -55])>>> aarray([-44, 1, -55, 3, 4])>>> a = np.arange(5)>>> np.put(a, 22, -5, mode='clip')>>> aarray([ 0, 1, 2, 3, -5])choice(a, size=None, replace=True, p=None)Generates a random sample from a given 1-D array .. versionadded:: 1.7.0Parameters-----------a : 1-D array-like or int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n)size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Default is None, in which case a single value is returned.replace : boolean, optional Whether the sample is with or without replacementp : 1-D array-like, optional The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.Returns--------samples : 1-D ndarray, shape (size,) The generated random samplesRaises-------ValueError If a is an int and less than zero, if a or p are not 1-dimensional, if a is an array-like of size 0, if p is not a vector of probabilities, if a and p have different lengths, or if replace=False and the sample size is greater than the population sizeSee Also---------randint, shuffle, permutationExamples---------Generate a uniform random sample from np.arange(5) of size 3:>>> np.random.choice(5, 3)array([0, 3, 4])>>> #This is equivalent to np.random.randint(0,5,3)Generate a non-uniform random sample from np.arange(5) of size 3:>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])array([3, 3, 0])Generate a uniform random sample from np.arange(5) of size 3 withoutreplacement:>>> np.random.choice(5, 3, replace=False)array([3,1,0])>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]Generate a non-uniform random sample from np.arange(5) of size3 without replacement:>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])array([2, 3, 0])Any of the above can be repeated with an arbitrary array-likeinstead of just integers. For instance:>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], dtype='|S11')58.减去矩阵的每一行的平均值(★★☆)
# Author: Warren WeckesserX = np.random.rand(5, 10)# Recent versions of numpyY = X - X.mean(axis=1, keepdims=True)# Older versions of numpyY = X - X.mean(axis=1).reshape(-1, 1)print(Y)笔者注:mean和reshape函数的使用方法:
mean(a, axis=None, dtype=None, out=None, keepdims=False)Compute the arithmetic mean along the specified axis.Returns the average of the array elements. The average is taken overthe flattened array by default, otherwise over the specified axis.`float64` intermediate and return values are used for integer inputs.Parameters----------a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted.axis : None or int or tuple of ints, optional Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. .. versionadded: 1.7.0 If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before.dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for floating point inputs, it is the same as the input dtype.out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See `doc.ufuncs` for details.keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`.Returns-------m : ndarray, see dtype parameter above If `out=None`, returns a new array containing the mean values, otherwise a reference to the output array is returned.See Also--------average : Weighted averagestd, var, nanmean, nanstd, nanvarNotes-----The arithmetic mean is the sum of the elements along the axis dividedby the number of elements.Note that for floating-point input, the mean is computed using thesame precision the input has. Depending on the input data, this cancause the results to be inaccurate, especially for `float32` (seeexample below). Specifying a higher-precision accumulator using the`dtype` keyword can alleviate this issue.Examples-------->>> a = np.array([[1, 2], [3, 4]])>>> np.mean(a)2.5>>> np.mean(a, axis=0)array([ 2., 3.])>>> np.mean(a, axis=1)array([ 1.5, 3.5])In single precision, `mean` can be inaccurate:>>> a = np.zeros((2, 512*512), dtype=np.float32)>>> a[0, :] = 1.0>>> a[1, :] = 0.1>>> np.mean(a)0.546875Computing the mean in float64 is more accurate:>>> np.mean(a, dtype=np.float64)0.55000000074505806 reshape(a, newshape, order='C')Gives a new shape to an array without changing its data.Parameters----------a : array_like Array to be reshaped.newshape : int or tuple of ints The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.order : {'C', 'F', 'A'}, optional Read the elements of `a` using this index order, and place the elements into the reshaped array using this index order. 'C' means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of indexing. 'A' means to read / write the elements in Fortran-like index order if `a` is Fortran *contiguous* in memory, C-like order otherwise.Returns-------reshaped_array : ndarray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the *memory layout* (C- or Fortran- contiguous) of the returned array.See Also--------ndarray.reshape : Equivalent method.Notes-----It is not always possible to change the shape of an array withoutcopying the data. If you want an error to be raise if the data is copied,you should assign the new shape to the shape attribute of the array:: >>> a = np.zeros((10, 2)) # A transpose make the array non-contiguous >>> b = a.T # Taking a view makes it possible to modify the shape without modifying # the initial object. >>> c = b.view() >>> c.shape = (20) AttributeError: incompatible shape for a non-contiguous arrayThe `order` keyword gives the index ordering both for *fetching* the valuesfrom `a`, and then *placing* the values into the output array.For example, let's say you have an array:>>> a = np.arange(6).reshape((3, 2))>>> aarray([[0, 1], [2, 3], [4, 5]])You can think of reshaping as first raveling the array (using the givenindex order), then inserting the elements from the raveled array into thenew array using the same kind of index ordering as was used for theraveling.>>> np.reshape(a, (2, 3)) # C-like index orderingarray([[0, 1, 2], [3, 4, 5]])>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshapearray([[0, 1, 2], [3, 4, 5]])>>> np.reshape(a, (2, 3), order='F') # Fortran-like index orderingarray([[0, 4, 3], [2, 1, 5]])>>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')array([[0, 4, 3], [2, 1, 5]])Examples-------->>> a = np.array([[1,2,3], [4,5,6]])>>> np.reshape(a, 6)array([1, 2, 3, 4, 5, 6])>>> np.reshape(a, 6, order='F')array([1, 4, 2, 5, 3, 6])>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2array([[1, 2], [3, 4], [5, 6]])>>> a=np.random.random(5.5)__main__:1: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future>>> a=np.random.random(5,5)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "mtrand.pyx", line 1101, in mtrand.RandomState.random_sample (numpy/random/mtrand/mtrand.c:13875)TypeError: random_sample() takes at most 1 positional argument (2 given)>>> a=np.random.random((5,5))>>> aarray([[ 0.55601468, 0.79038385, 0.72299353, 0.09075262, 0.31962592], [ 0.6715611 , 0.33806305, 0.7405167 , 0.9299074 , 0.17070615], [ 0.84808725, 0.25001323, 0.15195067, 0.45836408, 0.08134034], [ 0.18800557, 0.23962242, 0.37284134, 0.58488316, 0.57183337], [ 0.49037661, 0.73038881, 0.31046375, 0.82183011, 0.54166202]])>>> a.mean(axis=0)array([ 0.55080904, 0.46969427, 0.4597532 , 0.57714747, 0.33703356])>>> a-a.mean(axis=1)array([[ 0.06006056, 0.22023297, 0.36504242, -0.30068455, -0.25931834], [ 0.17560698, -0.23208783, 0.38256559, 0.53847022, -0.40823811], [ 0.35213313, -0.32013765, -0.20600045, 0.0669269 , -0.49760392], [-0.30794855, -0.33052846, 0.01489023, 0.19344599, -0.00711089], [-0.00557752, 0.16023793, -0.04748736, 0.43039294, -0.03728224]])>>> a.mean(axis=1)array([ 0.49595412, 0.57015088, 0.35795111, 0.39143717, 0.57894426])>>> a.mean(axis=1).reshape(-1,1)array([[ 0.49595412], [ 0.57015088], [ 0.35795111], [ 0.39143717], [ 0.57894426]])>>> a-a.mean(axis=1).reshape(-1,1)array([[ 0.06006056, 0.29442973, 0.22703941, -0.4052015 , -0.1763282 ], [ 0.10141022, -0.23208783, 0.17036582, 0.35975652, -0.39944474], [ 0.49013614, -0.10793788, -0.20600045, 0.10041296, -0.27661078], [-0.2034316 , -0.15181475, -0.01859583, 0.19344599, 0.1803962 ], [-0.08856765, 0.15144455, -0.2684805 , 0.24288585, -0.03728224]])>>> np.info(reshpae)Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'reshpae' is not defined>>> np.info(reshape) reshape(a, newshape, order='C')Gives a new shape to an array without changing its data.Parameters----------a : array_like Array to be reshaped.newshape : int or tuple of ints The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.order : {'C', 'F', 'A'}, optional Read the elements of `a` using this index order, and place the elements into the reshaped array using this index order. 'C' means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of indexing. 'A' means to read / write the elements in Fortran-like index order if `a` is Fortran *contiguous* in memory, C-like order otherwise.Returns-------reshaped_array : ndarray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the *memory layout* (C- or Fortran- contiguous) of the returned array.See Also--------ndarray.reshape : Equivalent method.Notes-----It is not always possible to change the shape of an array withoutcopying the data. If you want an error to be raise if the data is copied,you should assign the new shape to the shape attribute of the array:: >>> a = np.zeros((10, 2)) # A transpose make the array non-contiguous >>> b = a.T # Taking a view makes it possible to modify the shape without modifying # the initial object. >>> c = b.view() >>> c.shape = (20) AttributeError: incompatible shape for a non-contiguous arrayThe `order` keyword gives the index ordering both for *fetching* the valuesfrom `a`, and then *placing* the values into the output array.For example, let's say you have an array:>>> a = np.arange(6).reshape((3, 2))>>> aarray([[0, 1], [2, 3], [4, 5]])You can think of reshaping as first raveling the array (using the givenindex order), then inserting the elements from the raveled array into thenew array using the same kind of index ordering as was used for theraveling.>>> np.reshape(a, (2, 3)) # C-like index orderingarray([[0, 1, 2], [3, 4, 5]])>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshapearray([[0, 1, 2], [3, 4, 5]])>>> np.reshape(a, (2, 3), order='F') # Fortran-like index orderingarray([[0, 4, 3], [2, 1, 5]])>>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')array([[0, 4, 3], [2, 1, 5]])Examples-------->>> a = np.array([[1,2,3], [4,5,6]])>>> np.reshape(a, 6)array([1, 2, 3, 4, 5, 6])>>> np.reshape(a, 6, order='F')array([1, 4, 2, 5, 3, 6])>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2array([[1, 2], [3, 4], [5, 6]])fill
value when necessary) (★★★)新闻热点
疑难解答