How to use numpy's hstack?

16,189

Solution 1

I think this will do what you want:

a[:,[3,4]]

Solution 2

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]]

Solution 3

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]])
Share:
16,189
Sterling
Author by

Sterling

Updated on July 20, 2022

Comments

  • Sterling
    Sterling almost 2 years

    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.

  • Jaime
    Jaime over 10 years
    If the columns are consecutive, it may be a better idea to do a[:, 3:5], which returns a view, not a copy, of the array.