黑客|90个Numpy的有用的代码片段( 四 )


from numpy.lib import stride_tricks
def rolling(a window):
shape = (a.size - window + 1 window)
strides = (a.itemsize a.itemsize)
return stride_tricks.as_strided(a shape=shape strides=strides)
Z = rolling(np.arange(10) 3)
print(Z)
68、 如何对布尔值取反 , 或更改浮点数的符号?
# Author: Nathaniel J. Smith
Z = np.random.randint(02100)
np.logical_not(arr out=arr)
Z = np.random.uniform(-1.01.0100)
np.negative(arr out=arr)
69 、 考虑 2 组点 P0P1 描述线 (2d) 和一个点 p , 如何
计算从 p 到每条线 i (P0[i
P1[i
) 的距离?
def distance(P0 P1 p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:0
-p[...0
)*T[:0
+ (P0[:1
-p[...1
)*T[:1
) / L
U = U.reshape(len(U)1)
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))
P0 = np.random.uniform(-1010(102))
P1 = np.random.uniform(-1010(102))
p = np.random.uniform(-1010( 12))
print(distance(P0 P1 p))
70 、 2 组点 P0P1 描述线 (2d) 和一组点 P , 如何计算从每个点 j (P[j
) 到每条线 i (P0[i
P1[i
) 的距离?
# Author: Italmassov Kuanysh
# based on distance function from previous question
P0 = np.random.uniform(-10 10 (102))
P1 = np.random.uniform(-1010(102))
p = np.random.uniform(-10 10 (102))
print np.array([distance(P0P1p_i) for p_i in p
)
71、 一个任意数组 , 编写一个函数来提取具有固定形状并以给定元素为中心的子部分(必要时可以使用填充值填充)
# Author: Nicolas Rougier
Z = np.random.randint(010(1010))
shape = (55)
fill = 0
position = (11)
R = np.ones(shape dtype=Z.dtype)*fill
P = np.array(list(position)).astype(int)
Rs = np.array(list(R.shape)).astype(int)
Zs = np.array(list(Z.shape)).astype(int)
R_start = np.zeros((len(shape))).astype(int)
R_stop = np.array(list(shape)).astype(int)
Z_start = (P-Rs//2)
Z_stop = (P+Rs//2)+Rs%2
R_start = (R_start - np.minimum(Z_start0)).tolist()
Z_start = (np.maximum(Z_start0)).tolist()
R_stop = np.maximum(R_start (R_stop - np.maximum(Z_stop-Zs0))).tolist()
Z_stop = (np.minimum(Z_stopZs)).tolist()
r = [slice(startstop) for startstop in zip(R_startR_stop)

z = [slice(startstop) for startstop in zip(Z_startZ_stop)

R[r
= Z[z

print(Z)
print(R)
72、 一个数组 Z = [1234567891011121314
, 如何生成一个数组 R = [[123 4
[2345
[3456
... [11121314


# Author: Stefan van der Walt
Z = np.arange(115dtype=uint32)
R = stride_tricks.as_strided(Z(114)(44))
print(R)
73、 计算矩阵秩
# Author: Stefan van der Walt
Z = np.random.uniform(01(1010))
U S V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
74、 如何找到数组中出现频率最高的值?
Z = np.random.randint(01050)
print(np.bincount(Z).argmax())
75 、 从随机 10x10 矩阵中提取所有连续的 3x3 块
# Author: Chris Barker
Z = np.random.randint(05(1010))
n = 3
i = 1 + (Z.shape[0
-3)
j = 1 + (Z.shape[1
-3)
C = stride_tricks.as_strided(Z shape=(i j n n) strides=Z.strides + Z.strides)
print(C)
76 、 创建一个二维数组子类 , 使得 Z[ij
== Z[ji

# Author: Eric O. Lebigot
# Note: only works for 2d array and value setting using indices
class Symetric(np.ndarray):
def __setitem__(self (ij) value):
super(Symetric self).__setitem__((ij) value)
super(Symetric self).__setitem__((ji) value)
def symetric(Z):
return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)
S = symetric(np.random.randint(010(55)))
S[23
= 42
print(S)
77、 一组形状为 (nn) 的 p 个矩阵和一组形状为 (n1) 的 p 个向量、 如何一次计算 p 个矩阵乘积之和? (结果具有形状(n , 1))
# Author: Stefan van der Walt
p n = 10 20
M = np.ones((pnn))
V = np.ones((pn1))
S = np.tensordot(M V axes=[[0 2