Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 556
Sterling Avatar asked Nov 19 '13 16:11

Sterling


2 Answers

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]]
like image 95
dnf0 Avatar answered Oct 21 '22 14:10

dnf0


I think this will do what you want:

a[:,[3,4]]
like image 40
A.E. Drew Avatar answered Oct 21 '22 16:10

A.E. Drew