Lets say that I have these two numpy arrays:
a = np.array([1,1,1])
b = np.array([2,2,2])
How can I "mix" then to obtain the following:
c = np.array([1,2,1,2,1,2])
Does it exist a function like np.concatenate
, np.repeat
, np.tile
which I can use or I will have to make my own one?
It's not the prettiest, but you can do this:
>>> np.array(zip(a,b)).flatten()
array([1, 2, 1, 2, 1, 2])
You would however have to do the below in Python3
:
np.array(list(zip(a,b))).flatten()
As zip
no longer returns a list, but rather a generator (similar to range
).
Athough just for the record, it appears the fastest way is probably how John La Rooy suggested (using transpose then flatten):
$ python -m timeit 'import numpy as np; a = np.array(range(30)); b = np.array(range(30)); c = np.array(zip(a,b)).flatten()'
10000 loops, best of 3: 24.9 usec per loop
$ python -m timeit 'import numpy as np; a = np.array(range(30)); b = np.array(range(30)); c = np.array([a, b]).T.flatten()'
100000 loops, best of 3: 14.9 usec per loop
$ python -m timeit 'import numpy as np; a = np.array(range(30)); b = np.array(range(30)); c = np.vstack([a, b]).T.ravel()'
10000 loops, best of 3: 21.5 usec per loop