查看numpy的版本和配置
1 | import numpy as np |
np.zeros
默认$dtype$是浮点型的0
1 | np.zeros(10) # 一维 |
np.ndarray.itemsize
查看$ndarray$中一个元素的内存
1 | a = np.random.randn(3 , 4) |
reverse一个vector
1 | np.arange(10)[::-1] # 利用切片来转置 |
寻找ndarray的非0元素的下标
使用np.nonzero()
1 | a = np.arange(12).reshape(3 , 4) |
创建一个单位矩阵
np.eye
1 | np.eye(3 , 3) # dtype 为浮点型 |
np.random.random()
Return random floats in the half-open interval $[0.0, 1.0)$.
1 | np.random.random((3 , 3)) |
寻找ndarray的最大值和最小值
1 | a = np.arange(12).reshape(3 , 4) |
使一个array的周围都是0
1 | a = np.ones((5 , 5)) |
np.nan和np.inf的一些运算
1 | 0 * np.nan # nan |
np.diag(v , k)
v: array_like
按照k和v来判断矩阵的大小(是方阵)
1 | np.diag(1 + np.arange(4) , k = 1) # 对角线上一格 5 * 5 |
创建一个checkerboard pattern的矩阵
方法1:
1 | a = np.ones((8 , 8) , dtype = 'int') |
方法2:
1 | np.tile(np.array([[0 , 1] , [1 , 0]]) , (4 , 4)) |
给定一个array的维度,如何查看第i个元素的下标是多少
np.unravel_index
1 | np.unravel_index(99 , (6 , 7 , 8)) # shape = (6 , 7 , 8)的第99个元素的小标为 |
创建一个dtype来描述(RGBA)
1 | dtype1 = np.dtype([('r' , np.ubyte) , ('g' , np.ubyte) , ('b' , np.ubyte) , ('a' , np.ubyte)]) # 创建好类型 |
1 | a = np.array([(1 , 2 , 3 , 4) , (5 , 6 , 7 , 8)] , dtype = dtype1) |
将array中大于3且小于8的数取反
用与运算
1 | a = np.arange(11) |
求两个array的交集
np.intersect1d:求交集
1 | a = np.array([1 , 2 , 4 , 3 , 5]) |
获取当前的今天和明天的日期
1 | a = np.datetime64('today') # 获取今天的日期 |
1 | a = pd.Timestamp(a) |
获取2016年7月的全部日期(以天为单位)
修改dtye使得字符串变为时间
1 | np.arange('2016-07' , '2016-08' , dtype = 'datetime64[D]') # 换成Y就是年为单位,换成M就是月为单位 |
提取正数的整数部分 (4 种方法)
有关np.where的用法,参考:https://www.cnblogs.com/massquantity/p/8908859.html
1 | a = np.random.uniform(-5 , 10 , 10) |
1 | # 方法1: |
np.trunc
np.trunc: 此函数返回输入数组元素的截断值。输入值$x$的截断值$t$是更接近0的整数, 比$x$更接近零。
1 | a = np.array([-4.5375666 , 1.54911477, -3.74455161, -2.41802724, 3.17252821, 8.00279135, -4.8008351 , 5.53268438, -2.19521765, 8.72607842]) |
利用生成器方法来生成一个array
np.fromiter: Create a new 1-dimensional array from an iterable object.
1 | def func(n): |
np.add.reduce(ndarray , axis)
比np.sum更快
1 | a = array([1 , 2 , 3 , 4]) |
使一个array 只读(read-only)
1 | a = np.array([1 , 2 , 3]) |
将直角坐标变为极坐标
1 | a = np.random.randn(10 , 2) # 直角坐标 |
np.arctan2(y , x) 求出来的范围是$[-pi , pi]$
而np.arctan(y / x) 的范围是$[-pi/2 , pi/2]$
将矩阵的每列的最小值置1 (特殊的切片方式)
1 | a = np.random.randn(5 , 5) |
求[0,1]x[1,0]区域内所有坐标
np.meshgrid: 生成网格坐标
np.linspace: 生成等差数列
1 | a = np.ones((5 , 5) , dtype = [('x' , np.float) , ('y' , np.float)]) |
np.meshgrid
1 | # 对于2维矩阵来说,如果x坐标分成n份,y坐标分成m份,那么x的坐标矩阵就是mxn,y的坐标矩阵也是mxn |
np.subtract.outer
1 | np.subtract.outer(x , y): |
np.add.outer 也是类似
查看numpy的各种类型的最大值和最小值
1 | for dtype in (np.int16 , np.int32 , np.int64): |
np.atleast_2d
输入:arys1, arys2, … : array_like
函数作用:View inputs as arrays with at least two dimensions.
1 | a = np.arange(12).reshape(6 , 2) |
1 | np.atleast_2d(1 , 2 , [1 , 2]) # 都转为2d 的shape |
scipy.spatial.distance.cdist
更快地计算两点之间的距离
1 | Parameters |
1 | import scipy.spatial |
原地将float32 转为 int32
使用np.ndarray.view
numpy.ndarray.view中,提供对内存区域不同的切割方式,来完成数据类型的转换,而无须要对数据进行额外的copy,来节约内存空间。
1 | a = (np.random.rand(10) * 100).astype(np.float32) |
np.ndenumerate
numpy array 的 enumerate
1 | a = np.arange(6).reshape(2 , 3) |
1 | a = np.arange(6).reshape(6) |
np.ndindex
用于获取ndarray 的 index
1 | a = np.arange(6).reshape(2 , 3) |
生成一个2D Gaussian-like array
这里不是生成一个array,其符合高斯分布,而是其坐标中$y$是$x$的高斯函数
高斯函数:$f(x)=a e^{-\frac{(x-b)^{2}}{2 c^{2}}}$
- a表示得到曲线的高度;
- b(μ)是指曲线在x轴的中心;
- c(σ)指width(与半峰全宽有关);
1 | x , y = np.meshgrid(np.linspace(-1 , 1 , 10) , np.linspace(-1 , 1 , 10)) # 生成网格坐标 |
高斯函数和正态分布
高斯函数只是一种函数;
而正态分布是一个随机变量$x$,其概率密度符合高斯函数:
那么$x$就符合正态分布
np.put
1 | Parameters |
1 | a = np.arange(12) |
np.random.choice
在指定范围内随机选择几个数
1 | np.random.choice(range(10*10) , 3 , replace = False) # replace: 是否可以重复采样 |
keepdims 参数
就是保留原来ndarray的一些维度
1 | # 比如: |
数组按第n列排序
1 | a = np.random.randn(5 , 5) |
np.flat
当多维数组用一维坐标访问时用
1 | 61. Find the nearest value from a given value in an array (★★☆) |
np.bincount
详细,参考:https://blog.csdn.net/xlinsist/article/details/51346523
1 | a = np.random.randint(0 , 10 , 10) |
1 | 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★) |
1 | 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) |
1 | 68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★) |
np.unique
返回一个array的唯一的值序列,结果会排序
1 | 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★) |
在切片时加 None,补充一维
1 | a[: , : , None].shape , a[: , None , :].shape , a[None , : , :].shape , a[1:2 , : , None].shape |
如何交换array的一行
1 | 72. How to swap two rows of an array? (★★★) |
np.ndarray.repeat
1 | a |
np.roll
1 | Parameters |
1 | a = np.arange(12).reshape(3 , 4) |
1 | 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) |
np.repeat
1 | Parameters |
1 | np.repeat(np.arange(5) , [1 , 2 , 1 , 2 , 0]) |
1 | 74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) |
np.cumsum
Return the cumulative sum of the elements along a given axis. 即前缀和
1 | a = np.arange(5) |
1 | 75. How to compute averages using a sliding window over an array? (★★★) |
stride_tricks.as_strided
有关stride_tricks.as_strided 的用法,参考:https://zhuanlan.zhihu.com/p/64933417
1 | 76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★) |
negate a boolean,将布尔数组取反
使用 np.logical_not
1 | Z = np.random.randint(0,2,100) |
change the sign of a float inplace
使用np.negative
1 | Z = np.random.uniform(-1.0,1.0,10) |
计算点到直线的距离
可以利用向量积来求,由于向量积是两个向量所围成的平行四边形的面积,所以可以利用面积/底边来求高,这个高即是点到直线的距离
np.cross 是求向量的向量积,有关向量积的内容参考:https://www.bilibili.com/video/av6341515
1 | 78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★) |
计算矩阵的秩
先对矩阵进行奇异值分解(SVD),然后利用 非0奇异值的个数 = 矩阵的秩这一性质来求
有关奇异值分解(SVD),参考: https://www.cnblogs.com/endlesscoding/p/10033527.html 和 https://blog.csdn.net/weixin_43991178/article/details/104906655
1 | Z = np.random.uniform(0,1,(10,8)) |
np.tensordot
np.tensordot,参考:
https://blog.csdn.net/weixin_28710515/article/details/90230842
1 | 86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★) |
np.argpartition
np.argpartition: 第一个参数 a 如果是a的话,是升序排列,如果是-a的话,就是降序排列 第二个参数kth,表示要选择的前k个元素,那么就把这前k个元素的索引排到前面,并不会排序,而只会筛选出这前几位元素,返回值是数组的索引。
1 | a = np.random.randint(0 , 10 , (2 , 20)) |
1 | 89. How to get the n largest values of an array (★★★) |
记录数组和结构数组
记录数组和结构数组的定义和区别,参考:https://blog.csdn.net/qq_27825451/article/details/102457045
1 | 91. How to create a record array from a regular array? (★★★) |
np.unpackbits
将8位长整型元素数组展开成二进制形式
1 | 95. Convert a vector of ints into a matrix binary representation (★★★) |
如何判断一个1d的array的所有元素都相等
1 | a = np.array([1] * 5) |
1 | 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★) |
np.indices
np.indices函数的作用是返回一个代表网格中所有序号的矩阵(给定shape)。
详细,参考:https://blog.csdn.net/isunLt/article/details/107620828
1 | 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★) |
如何实现等距采样
等距采样就是每隔相等的距离采一次样。
可以采用一维线性插值法来获取不同的距离所对应的样本的值,一维线性插值法的函数:np.interp,详细,参考:https://blog.csdn.net/hfutdog/article/details/87386901
1 | 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? |
np.diff
后一个元素减去前一个元素
1 | np.diff(np.array([1 , 2 , 3 , 4])) |
np.inner
返回两个向量的内积
1 | np.inner(np.array([1 , 2 , 3]) , np.array([1 , 2 , 3])) |
ndarray 的 slice 切片操作
1 | a = np.arange(25).reshape(5 , 5) |
x.setitem(i, y) <==> x[i]=y
1 | 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★) |
ndarray 子类实体的创建
参考:https://blog.csdn.net/SAKURASANN/article/details/102750468
63. Create an array class that has a name attribute (★★☆)
1 | # python中cls代表的是类的本身,相对应的self则是类的一个实例对象。 |
__new__
参考:
