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


[0 1

)
print(S)
# It works because:
# M is (pnn)
# V is (pn1)
# Thus summing over the paired axes 0 and 0 (of M and V independently)
# and 2 and 1 to remain with a (n1) vector.
78 、 考虑一个 16x16 数组 , 如何获得块的和(块大小为 4x4)?
# Author: Robert Kern
Z = np.ones(1616)
k = 4
S = np.add.reduceat(np.add.reduceat(Z np.arange(0 Z.shape[0
k) axis=0)
np.arange(0 Z.shape[1
k) axis=1)
79 、 如何使用 numpy 数组实现 Game of Life?
# Author: Nicolas Rougier
def iterate(Z):
# Count neighbours
N = (Z[0:-20:-2
+ Z[0:-21:-1
+ Z[0:-22:
+
Z[1:-10:-2
+ Z[1:-12:
+
Z[2: 0:-2
+ Z[2: 1:-1
+ Z[2: 2:
)
# Apply rules
birth = (N==3) & (Z[1:-11:-1
==0)
survive = ((N==2) | (N==3)) & (Z[1:-11:-1
==1)
Z[...
= 0
Z[1:-11:-1
[birth | survive
= 1
return Z
Z = np.random.randint(02(5050))
for i in range(100): Z = iterate(Z)
80、获得数组的n个最大的值
Z = np.arange(10000)
np.random.shuffle(Z)
n = 5
# Slow
print (Z[np.argsort(Z)[-n:

)
# Fast
print (Z[np.argpartition(-Zn)[:n

)
81、构建笛卡尔积(每个项的每个组合)
# Author: Stefan Van der Walt
def cartesian(arrays):
arrays = [np.asarray(a) for a in arrays

shape = (len(x) for x in arrays)
ix = np.indices(shape dtype=int)
ix = ix.reshape(len(arrays) -1).T
for n arr in enumerate(arrays):
ix[: n
= arrays[n
[ix[: n


return ix
print (cartesian(([1 2 3
[4 5
[6 7
)))
82、从一个常规数组创建一个records数组?
Z = np.array([(\"Hello\" 2.5 3)
(\"World\" 3.6 2)
)
R = np.core.records.fromarrays(Z.Tnames='col1 col2 col3'
formats = 'S8 f8 i8')
83、一个大向量Z , 使用3种不同的方法计算Z的3次方
Author: Ryan G.
x = np.random.rand(5e7)
%timeit np.power(x3)
1 loops best of 3: 574 ms per loop
%timeit x*x*x
1 loops best of 3: 429 ms per loop
%timeit np.einsum('iii->i'xxx)
1 loops best of 3: 244 ms per loop
84、形状为(83)和(22)的两个数组A和B、如何在A中找到包含B每一行元素的行不管B中元素的顺序是什么?
# Author: Gabe Schwartz
A = np.random.randint(05(83))
B = np.random.randint(05(22))
C = (A[... np.newaxis np.newaxis
== B)
rows = (C.sum(axis=(123)) >= B.shape[1
).nonzero()[0

print(rows)
85、一个10x3矩阵 , 提取不相等值的行(例如[223
)
# Author: Robert Kern
Z = np.random.randint(05(103))
E = np.logical_and.reduce(Z[:1:
== Z[::-1
axis=1)
U = Z[~E

print(Z)
print(U)
86、将一个int型向量转换为一个矩阵二进制表示形式
# Author: Warren Weckesser
I = np.array([0 1 2 3 15 16 32 64 128
)
B = ((I.reshape(-11) & (2**np.arange(8))) != 0).astype(int)
print(B[:::-1
)
# Author: Daniel T. McDonald
I = np.array([0 1 2 3 15 16 32 64 128
dtype=np.uint8)
print(np.unpackbits(I[: np.newaxis
axis=1))
87、给定一个二维数组 , 如何提取唯一的行?
# Author: Jaime Fernández del Río
Z = np.random.randint(02(63))
T = np.ascontiguousarray(Z).view(np.dtype((np.void Z.dtype.itemsize * Z.shape[1
)))
_ idx = np.unique(T return_index=True)
uZ = Z[idx

print(uZ)
88、考虑两个向量A和B , 使用einsum求sum、* 、inner、outer
# Author: Alex Riley
# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/
np.einsum('i->' A) # np.sum(A)
np.einsum('ii->i' A B) # A * B
np.einsum('ii' A B) # np.inner(A B)
np.einsum('ij' A B) # np.outer(A B)
89 、 由两个向量(X , Y)描述的路径 , 如何使用等距样本对其进行采样?
# Author: Bas Swinckels
phi = np.arange(0 10*np.pi 0.1)
a = 1
x = a*phi*np.cos(phi)
y = a*phi*np.sin(phi)
dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
r = np.zeros_like(x)