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

use*_*430 15 python arrays numpy

我想交错两个相同大小的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
Run Code Online (Sandbox Code Playgroud)

输出

[[ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]
 [ 1.  1.  1.]
 [ 0.  0.  0.]]
Run Code Online (Sandbox Code Playgroud)

是否有更干净,更快,更好,仅限numpy的方式?

Jos*_*del 16

这可能有点清楚:

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
Run Code Online (Sandbox Code Playgroud)

我猜也好,它可能还要快一点.


oka*_*tal 7

我发现使用以下方法numpy.hstack()非常可读:

\n\n
import numpy as np\n\na = np.ones((2,3))\nb = np.zeros_like(a)\n\nc = np.hstack([a, b]).reshape(4, 3)\n\nprint(c)\n
Run Code Online (Sandbox Code Playgroud)\n\n

输出:

\n\n
[[ 1.  1.  1.]\n [ 0.  0.  0.]\n [ 1.  1.  1.]\n [ 0.  0.  0.]]\n
Run Code Online (Sandbox Code Playgroud)\n\n

很容易将其推广到相同形状的数组列表:

\n\n
arrays = [a, b, c,...]\n\nshape = (len(arrays)*a.shape[0], a.shape[1])\n\ninterleaved_array = np.hstack(arrays).reshape(shape)\n
Run Code Online (Sandbox Code Playgroud)\n\n

它似乎比 @JoshAdel 在小数组上接受的答案慢一点,但在大数组上同样快或更快:

\n\n
a = np.random.random((3,100))\nb = np.random.random((3,100))\n\n%%timeit\n...: C = np.empty((a.shape[0]+b.shape[0],a.shape[1]))\n...: C[::2,:] = a\n...: C[1::2,:] = b\n...:\n\nThe slowest run took 9.29 times longer than the fastest. This could mean that an intermediate result is being cached.\n100000 loops, best of 3: 3.3 \xc2\xb5s per loop\n\n%timeit c = np.hstack([a,b]).reshape(2*a.shape[0], a.shape[1])\nThe slowest run took 5.06 times longer than the fastest. This could mean that an intermediate result is being cached. \n100000 loops, best of 3: 10.1 \xc2\xb5s per loop\n\na = np.random.random((4,1000000))\nb = np.random.random((4,1000000))\n\n%%timeit\n...: C = np.empty((a.shape[0]+b.shape[0],a.shape[1]))\n...: C[::2,:] = a\n...: C[1::2,:] = b\n...: \n\n10 loops, best of 3: 23.2 ms per loop\n\n%timeit c = np.hstack([a,b]).reshape(2*a.shape[0], a.shape[1])\n10 loops, best of 3: 21.3 ms per loop\n
Run Code Online (Sandbox Code Playgroud)\n


eca*_*mur 5

您可以堆叠,转置和重塑形状:

numpy.dstack((A, B)).transpose(0, 2, 1).reshape(A.shape[0]*2, A.shape[1])
Run Code Online (Sandbox Code Playgroud)