Sterling
Sterling

Reputation: 4213

How to use numpy's hstack?

I have one large numpy.ndarray array that I want to extract the 4th and 5th columns out of and put those columns into a 2D array. The [i,0] element should be the value on the 4th column and [i,1] should be the element from the 5th column.

I trying to use the numpy.hstack function to do this.

a = numpy.asarray([1, 2, 3, 4, 5])
for i in range(5):
    a = numpy.vstack([a, numpy.asarray([1, 2, 3, 4, 5])])

combined = np.hstack([a[:,3], a[:,4]])

However, this simply gives me an nx1 array. I have tried multiple approaches using concatenate that look like these examples:

combined = np.concatenate([a[:,3], a[:,4]])

combined = np.concatenate([a[:,3], a[:,4]], axis=1)

combined = np.concatenate([a[:,3].T, a[:,4].T])

I feel like hstack is the function I want, but I can't seem to figure out how to make it give me an nx2 array. Can anyone point me in the right direction? Any help is appreciated.

Upvotes: 11

Views: 16986

Answers (3)

dnf0
dnf0

Reputation: 1649

Just slice out your data as follows:

X = [[0 1 2 3 4]
     [0 1 2 3 4]
     [0 1 2 3 4]
     [0 1 2 3 4]]

slicedX = X[:,3:5]

results in:

[[3 4]
 [3 4]
 [3 4]
 [3 4]]

Upvotes: 4

mdml
mdml

Reputation: 22882

You can also use zip:

>>> c = numpy.array( zip( a[:, 3], a[:, 4]) )
>>> c
array([[4, 5],
       [4, 5],
       [4, 5],
       [4, 5],
       [4, 5],
       [4, 5]])

Upvotes: 1

A.E. Drew
A.E. Drew

Reputation: 2137

I think this will do what you want:

a[:,[3,4]]

Upvotes: 3

Related Questions