Skip to content Skip to sidebar Skip to footer

Index Of True And False Of A Numpy Array

Code: import numpy as np a = np.arange(5) print(a[True]) print(a[False]) Result: [[0 1 2 3 4]] [] For above code when I am passing True to index of a numpy array it's

Solution 1:

Your example---applying a scalar, or 0D---boolean mask to a 1D array yields

print(a[True])
# [[0 1 2 3 4]]print(a[False])
# []

For clarity, especially w.r.t. the second (False) case let us query the shapes

print(a[True].shape)
# (1, 5)print(a[False].shape)
# (0, 5)

Now that is at first sight slightly puzzling. Why the extra dimension?

Let's start from a less edgy case and work out why this is the logical behavior:

x = np.arange(6).reshape(3,2)
m2 = np.array([[True,False],[True,True],[False,True]])
m1 = np.array([True,False,True])
m0 = np.array(True)

We have created a 2D array and matching 2D,1D and 0D masks.

Masking with a 2D mask gives a 1D result

x[m2]
# array([0, 2, 3, 5])

Masking with a 1D mask selects entire rows, hence gives a 2D result

x[m1]
# array([[0, 1],
#        [4, 5]])

We could verify in higher dimesions also, that removing a dimension from the mask adds one to the result.

Therefore it is logical that masking with 0D we shold indeed get one dimension more than we started with. A 2D mask selects individual points (0D -> list of those: 1D), a 1D mask selected entire rows (1D -> list of those: 2D); consequently, a 0D mask should and does select entire sheets (2D -> list of those: 3D); as the base array is 2D a sheet is the whole of it.

x[m0]
# array([[[0, 1],
#         [2, 3],
#         [4, 5]]])

x[m0].ndim
# 3

In general:

x[m2].ndim == x.ndim - m2.ndim + 1
# True 
x[m1].ndim == x.ndim - m1.ndim + 1
# True
x[m0].ndim == x.ndim - m0.ndim + 1
# True

Solution 2:

a be your numpy array and i.e [0,1,2,3,4] you suppose to put condition on index if condition is satisfied then it will return that element if not then discard those element. here you are putting True which mean every element satisfied this condition which is True in every case if False then non of the element satisfied. check this section

Boolean or “mask” index arrays

Post a Comment for "Index Of True And False Of A Numpy Array"