本节书摘来自异步社区《Python数据分析》一书中的第2章,第2.10节,作者【印尼】Ivan Idris,更多章节内容可以访问云栖社区“异步社区”公众号查看
布尔型索引是指根据布尔型数组来索引元素的方法,属于花式索引系列。因为布尔型索引是花式索引的一个分类,所以它们的使用方法基本相同。
下面用代码(详见本书代码包中的boolean_indexing.py文件)具体演示其使用方法:
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) plt.show()上述代码利用一种特殊的迭代器对象来索引元素,下面进行简单说明。
1.在对角线上画点。
这类似于花式索引,不过这里选择的是照片对角线上可以被4整除的那些位置上的点。
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)2.根据元素值的情况置0``。
选取数组值介于最大值的1/4到3/4的那些元素,将其置0。
lena2[(lena > lena.max()/4) & (lena < 3 * lena.max()/4)] = 03.两幅新照片如图2-7所示。
相关资源:敏捷开发V1.0.pptx