Splicing NumPy arrays

Question:

I am having a problem splicing together two arrays. Let’s assume I have two arrays:

a = array([1,2,3])
b = array([4,5,6])

When I do vstack((a,b)) I get

[[1,2,3],[4,5,6]]

and if I do hstack((a,b)) I get:

[1,2,3,4,5,6]

But what I really want is:

[[1,4],[2,5],[3,6]]

How do I accomplish this without using for loops (it needs to be fast)?

Asked By: Siggi

||

Answers:

Try column_stack()?

http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html

Alternatively,

vstack((a,b)).T
Answered By: Amber

I forgot how to transpose NumPy arrays, but you could do:

at = transpose(a)
bt = transpose(b)

result = vstack((a,b))
Answered By: Nathan Fellman

You are probably looking for shape manipulation of the array. You can look in the "Tentative NumPy Tutorial, Array Creation".

Answered By: anijhaw

column_stack.

Answered By: Philipp
>>> c = [list(x) for x in zip(a,b)]
>>> c
[[1, 4], [2, 5], [3, 6]]

or

>>> c = np.array([list(x) for x in zip(a,b)])
>>> c
array([[1, 4],
       [2, 5],
       [3, 6]])

depending on what you’re looking for.

Answered By: mtrw
numpy.vstack((a, b)).T
Answered By: Cheery
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.