pythonnumpyslice

numpy python - slicing rows and columns at the same time


I have a numpy matrix with 130 X 13. Say I want to select a specific set of rows meeting a condition and a subset of columns -

trainx[trainy==label,[0,6]]

The above code does not work and throws an error - IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (43,) (2,).

However if I do it in 2 steps - first subset rows and then columns, it works. Is it something weird or numpy works this way?

temp1 = trainx[trainy==label,:]
temp1 = temp1[:,[0,6]]

Solution

  • you can simply chain the indexing like

    trainx[trainy==label][:, [0,6]]
    

    Runable Example

    arr = np.random.rand(130,13)
    arr[arr[:,0]>0.5][:, [0,6]]