在Python中交错两个NumPy数组的行

17

我想交错两个大小相同的numpy数组的行。 我想出了这个解决方案。

# A and B are same-shaped arrays
A = numpy.ones((4,3))
B = numpy.zeros_like(A)
C = numpy.array(zip(A[::1], B[::1])).reshape(A.shape[0]*2, A.shape[1])
print(C)

输出

[[ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]]

有没有一种更干净、更快、更好、基于numpy的方法?


是的,你的问题确实缺少一个“但是(BUT)”块。 - Samuele Mattiuzzo
如果让我猜的话,我会说“BUT”块应该是这样的——“但我想知道是否可以在numpy中完成所有操作,而不需要使用zip”。 - mgilson
谢谢你教我zeros_like函数!有点尴尬,我之前不知道它的存在。 - John Vinyard
是的,"但是"块将是"是否有一种更清洁、更快、更好、仅使用numpy的方法?" - user394430
1
@user394430 然后将其添加到问题中。 - Brad Gilbert
3个回答

21

或许更清晰的做法是:

A = np.ones((4,3))
B = np.zeros_like(A)

C = np.empty((A.shape[0]+B.shape[0],A.shape[1]))

C[::2,:] = A
C[1::2,:] = B

而且我猜它可能会更快一些。


7
我觉得以下使用 numpy.hstack() 的方法非常易读:
import numpy as np

a = np.ones((2,3))
b = np.zeros_like(a)

c = np.hstack([a, b]).reshape(4, 3)

print(c)

输出:

[[ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]]

很容易将其推广到具有相同形状的数组列表:
arrays = [a, b, c,...]

shape = (len(arrays)*a.shape[0], a.shape[1])

interleaved_array = np.hstack(arrays).reshape(shape)

这个方法在小数组上比@JoshAdel的被接受的答案慢一点,但在大数组上同样快或更快:

a = np.random.random((3,100))
b = np.random.random((3,100))

%%timeit
...: C = np.empty((a.shape[0]+b.shape[0],a.shape[1]))
...: C[::2,:] = a
...: C[1::2,:] = b
...:

The slowest run took 9.29 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.3 µs per loop

%timeit c = np.hstack([a,b]).reshape(2*a.shape[0], a.shape[1])
The slowest run took 5.06 times longer than the fastest. This could mean that an intermediate result is being cached. 
100000 loops, best of 3: 10.1 µs per loop

a = np.random.random((4,1000000))
b = np.random.random((4,1000000))

%%timeit
...: C = np.empty((a.shape[0]+b.shape[0],a.shape[1]))
...: C[::2,:] = a
...: C[1::2,:] = b
...: 

10 loops, best of 3: 23.2 ms per loop

%timeit c = np.hstack([a,b]).reshape(2*a.shape[0], a.shape[1])
10 loops, best of 3: 21.3 ms per loop

6

您可以进行堆叠、转置和重塑:

numpy.dstack((A, B)).transpose(0, 2, 1).reshape(A.shape[0]*2, A.shape[1])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接