我尝试将一个数组(A(2-D))复制到另一个数组(B(3-D)),其形状如下
A 是 m * n 数组,B 是 m * n * p 数组
我尝试了以下代码,但速度非常慢,比如 1 秒/帧
for r in range (0, h):
for c in range (0, w):
x = random.randint(0, 20)
B[r, c, x] = A[r, c]
我还阅读了一些有关精美索引的网站,但我仍然不知道如何将其应用到我的网站中。
最佳答案
我提出了一个使用数组索引的解决方案。 M
、N
、P
分别是 (m,n)
索引数组,指定 m*n 个元素B
将从A
接收数据。
def indexing(A, p):
m,n = A.shape
B = np.zeros((m,n,p), dtype=int)
P = np.random.randint(0, p, (m,n))
M, N = np.indices(A.shape)
B[M,N,P] = A
return B
为了比较,原始循环和使用 shuffle 的解决方案
def looping(A, p):
m, n = A.shape
B = np.zeros((m,n,p), dtype=int)
for r in range (m):
for c in range (n):
x = np.random.randint(0, p)
B[r, c, x] = A[r, c]
return B
def shuffling(A, p):
m, n = A.shape
B = np.zeros((m,n,p), dtype=int)
B[:,:,0] = A
map(np.random.shuffle, B.reshape(m*n,p))
return B
对于 m,n,p = 1000,1000,20,时间为:
looping: 1.16 s
shuffling: 10 s
indexing: 271 ms
对于较小的 m,n,循环速度最快。我的索引解决方案需要更多时间来设置,但实际分配速度很快。洗牌解决方案的迭代次数与原始解决方案的迭代次数相同。
M
、N
数组不必是满的。它们可以分别是列数组和行数组
M = np.arange(m)[:,None]
N = np.arange(n)[None,:]
或
M,N = np.ogrid[:m,:n]
这可以节省一些时间,对于小型测试用例比大型测试用例更是如此。
可重复的版本:
def indexing(A, p, B=None):
m, n = A.shape
if B is None:
B = np.zeros((m,n,p), dtype=int)
for r in range (m):
for c in range (n):
x = np.random.randint(0, p)
B[r, c, x] = A[r, c]
return B
indexing(A,p,indexing(A,p))
如果A
的大小与B
的第1个2暗淡的大小不同,则必须更改索引范围。 A
也不必是二维数组:
B[[0,0,2],[1,1,0],[3,4,5]] = [10,11,12]
关于python - 将 numpy 数组从一个(2-D)复制到另一个(3-D),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26327137/