When using logical indexing on numpy arrays, different behaviours occur based on whether the indices were boolean or integer (1/0). This answer states that, as of Python 3.x,
True
andFalse
are keywords and will always be equal to1
and0
.
Can someone explain what causes this behaviour?
MWE to replicate (Python 3.7.3, Numpy 1.16.3):
import numpy as np
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [True, True, True, True, True, False, False, False, False, False]
c = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
npa = np.asarray(a)
npb = np.asarray(b)
npc = np.asarray(c)
print(npa[b]) # [0 1 2 3 4]
print(npa[npb]) # [0 1 2 3 4]
print(npa[c]) # [1 1 1 1 1 0 0 0 0 0]
print(npa[npc]) # [1 1 1 1 1 0 0 0 0 0]