O'Reilly logo

Python Data Analysis by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Indexing NumPy arrays with Booleans

Boolean indexing is indexing based on a Boolean array and falls in the family of fancy indexing. Since Boolean indexing is a kind of fancy indexing, the way it works is essentially the same.

The following is the code for this segment (refer to boolean_indexing.py in this book's code bundle):

import scipy.misc import matplotlib.pyplot as plt import numpy as np lena = scipy.misc.lena() def get_indices(size): arr = np.arange(size) return arr % 4 == 0 lena1 = lena.copy() xindices = get_indices(lena.shape[0]) yindices = get_indices(lena.shape[1]) lena1[xindices, yindices] = 0 plt.subplot(211) plt.imshow(lena1) lena2 = lena.copy() lena2[(lena > lena.max()/4) & (lena < 3 * lena.max()/4)] = 0 plt.subplot(212) plt.imshow(lena2) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required