Sterling Sterling - 1 month ago 5
Python Question

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.

Answer

I think this will do what you want:

a[:,[3,4]]