Grzegorz Rut
Grzegorz Rut

Reputation: 215

Merging 1D arrays into a 2D array

Is there a built-in function to join two 1D arrays into a 2D array? Consider an example:

X=np.array([1,2])
y=np.array([3,4])
result=np.array([[1,3],[2,4]])

I can think of 2 simple solutions. The first one is pretty straightforward.

np.transpose([X,y])

The other one employs a lambda function.

np.array(list(map(lambda i: [a[i],b[i]], range(len(X)))))

While the second one looks more complex, it seems to be almost twice as fast as the first one.

Edit A third solution involves the zip() function.

np.array(list(zip(X, y)))

It's faster than the lambda function but slower than column_stack solution suggested by @Divakar.

np.column_stack((X,y))

Upvotes: 4

Views: 17190

Answers (2)

Ferran Parés
Ferran Parés

Reputation: 636

Take into consideration scalability. If we increase the size of the arrays, complete numpy solutions are quite faster than solutions involving python built-in operations:

np.random.seed(1234)
X = np.random.rand(10000)
y = np.random.rand(10000)

%timeit np.array(list(map(lambda i: [X[i],y[i]], range(len(X)))))
6.64 ms ± 32.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.array(list(zip(X, y)))
4.53 ms ± 33.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.column_stack((X,y))
19.2 µs ± 30.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.transpose([X,y])
16.2 µs ± 247 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.vstack((X, y)).T
14.2 µs ± 94.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Taking into account all proposed solutions, np.vstack(X,y).T is the fastest when working with greater array sizes.

Upvotes: 3

Austin
Austin

Reputation: 26057

This is one way:

import numpy as np
X = np.array([1,2])
y = np.array([3,4])
result = np.vstack((X, y)).T
print(result)

# [[1 3]
#  [2 4]]     

Upvotes: 3

Related Questions