假设我有一个NumPy
数组A
形状(N,N,N)
。由此,我形成2D
形状B
(N,N)
形状B = np.column_stack( tuple(A[i,:,i] for i in range(N)) )
,如下所示:
i-th
换句话说,对于2D
的{{1}} A
切片,我会选择它i-th
列;然后我stack
这些列形成B
。
我的问题是:
是否有更有效的方法(NumPy
索引/切片)从B
构建A
;主要是,是否可以消除for
2D
的{{1}}个切片上的内A
循环?
答案 0 :(得分:1)
您可以使用advanced indexing:
idx = np.arange(N) # or idx = range(N)
A[idx,:,idx].T
实施例:
import numpy as np
A = np.arange(27).reshape(3,3,3)
idx = np.arange(3)
A[idx,:,idx].T
#array([[ 0, 10, 20],
# [ 3, 13, 23],
# [ 6, 16, 26]])
np.column_stack( tuple(A[i,:,i] for i in range(3)) )
#array([[ 0, 10, 20],
# [ 3, 13, 23],
# [ 6, 16, 26]])
计时:对于大型数组来说它更快
def adv_index(N):
idx = range(N)
return A[idx,:,idx].T
N = 100
import numpy as np
A = np.arange(N*N*N).reshape(N,N,N)
%timeit np.column_stack(tuple(A[i,:,i] for i in range(N)))
# The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached.
# 1000 loops, best of 3: 210 µs per loop
%timeit adv_index(N)
# The slowest run took 5.87 times longer than the fastest. This could mean that an intermediate result is being cached.
# 10000 loops, best of 3: 51.1 µs per loop
(np.column_stack(tuple(A[i,:,i] for i in range(N))) == adv_index(N)).all()
# True