Подтвердить что ты не робот

Перемешать строки из двух массивов numpy в Python

Я хотел бы чередовать строки из двух массивов 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?

4b9b3361

Ответ 1

Это может быть немного понятнее:

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

и это, вероятно, немного быстрее, я думаю.

Ответ 2

Вы можете складывать, переносить и изменять форму:

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

Ответ 3

Я нахожу следующий подход, используя 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