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)?
Answers:
Try column_stack()
?
http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html
Alternatively,
vstack((a,b)).T
I forgot how to transpose NumPy arrays, but you could do:
at = transpose(a)
bt = transpose(b)
result = vstack((a,b))
You are probably looking for shape manipulation of the array. You can look in the "Tentative NumPy Tutorial, Array Creation".
column_stack
.
>>> 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.
numpy.vstack((a, b)).T
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)?
Try column_stack()
?
http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html
Alternatively,
vstack((a,b)).T
I forgot how to transpose NumPy arrays, but you could do:
at = transpose(a)
bt = transpose(b)
result = vstack((a,b))
You are probably looking for shape manipulation of the array. You can look in the "Tentative NumPy Tutorial, Array Creation".
column_stack
.
>>> 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.
numpy.vstack((a, b)).T