python布尔型数组_《Python数据分析》一2.10 用布尔型变量索引NumPy数组

本节书摘来自异步社区《Python数据分析》一书中的第2章,第2.10节,作者【印尼】Ivan Idris,更多章节内容可以访问云栖社区“异步社区”公众号查看

2.10 用布尔型变量索引NumPy数组

布尔型索引是指根据布尔型数组来索引元素的方法,属于花式索引系列。因为布尔型索引是花式索引的一个分类,所以它们的使用方法基本相同。

下面用代码(详见本书代码包中的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)] =

0

3.两幅新照片如图2-7所示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值