pythonnumpyindexingpython-3.7numpy-indexing

Numpy Indexing problem..... Advance indexing what is X[0] doing here?


import numpy as np

X = np.array([[0, 1, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1], [1, 0, 1, 0]])

y = np.array([0, 1, 0, 1])

counts = {}

print(X[y == 0])

# prints = [[0 1 0 1]
# [0 0 0 1]]

I want to know why X[y==0] printing two data point. Shouldn't it print only [0 1 0 1] ?

because X[0]?


Solution

  • y == 0 gives an array with same dimensions as y, with elements True where the corresponding element in y is 0, and False otherwise.

    Here, y has 0 elements at indices 0 and 2. So, X[y == 0] gives you an array containing X[0] and X[2].