Home > Mobile >  NumPy concat by turns
NumPy concat by turns

Time:05-24

How to combine 2 array by turns from

arr_1 = np.full((5,), 0)
arr_2 = np.full((5,), 1)

to

[0,1,0,1,0,1,0,1,0,1]

? thanks

CodePudding user response:

Given two arrays you can stack and then transpose them. Then just flatten it out:

import numpy as np

arr_1 = np.full((5,), 0)
arr_2 = np.full((5,), 1)

np.stack([arr_1, arr_2]).T.ravel()
#array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

This works by first stacking:

np.stack([arr_1, arr_2])
# array([[0, 0, 0, 0, 0],
#        [1, 1, 1, 1, 1]])

Then transposing:

np.stack([arr_1, arr_2]).T
# array([[0, 1],
#        [0, 1],
#        [0, 1],
#        [0, 1],
#        [0, 1]])

Then ravel() reads them off the contiguous flattened array.

Edit

As Nin17 points out in the comments stack() takes an axis argument, which avoids the transpose:

np.stack([arr_1, arr_2], 1).ravel()
# array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

This is a nice performance improvement.

CodePudding user response:

You can do that like so:

import numpy as np
a = np.array([0, 1])
repeated = np.tile(a, 5)

Result:

array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

Documentation.

  • Related