Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy union arrays in order

Tags:

python

numpy

I've got three different numpy arrays

a = array([ 0,  3,  6,  9, 12])
b = array([ 1,  4,  7, 10, 13])
c = array([ 2,  5,  8, 11, 14])

How can I join them using numpy methods that

d = array[(0,1,2,3,4,...,12,13,14)]

I don't want to write a loop like

for i in range(len(a)):
 [...]

This is only an example in my project the arrays are not sorted and I want to keep their order.

like image 856
glethien Avatar asked Feb 20 '23 14:02

glethien


1 Answers

You can transpose and flatten the arrays:

d = numpy.array([a, b, c]).T.flatten()

An alternative way to combine the arrays is to use numpy.vstack():

d = numpy.vstack((a, b, c)).T.flatten()

(I don't know which one is faster, by the way.)

Edit: In response to the answer by Nicolas Barbey, here is how to make do with copying the data only once:

d = numpy.empty((len(a), 3), dtype=a.dtype)
d[:, 0], d[:, 1], d[:, 2] = a, b, c
d = d.ravel()

This code ensures that the data is layed out in a way that ravel() does not need to make a copy, and indeed it is quite a bit faster than the original code on my machine:

In [1]: a = numpy.arange(0, 30000, 3)
In [2]: b = numpy.arange(1, 30000, 3)
In [3]: c = numpy.arange(2, 30000, 3)
In [4]: def f(a, b, c):
   ...:     d = numpy.empty((len(a), 3), dtype=a.dtype)
   ...:     d[:, 0], d[:, 1], d[:, 2] = a, b, c
   ...:     return d.ravel()
   ...: 
In [5]: def g(a, b, c):
   ...:     return numpy.vstack((a, b, c)).T.ravel()
   ...: 
In [6]: %timeit f(a, b, c)
10000 loops, best of 3: 34.4 us per loop
In [7]: %timeit g(a, b, c)
10000 loops, best of 3: 177 us per loop
like image 58
Sven Marnach Avatar answered Feb 22 '23 04:02

Sven Marnach