zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

2023-09-11 14:17:44 时间

本节书摘来自异步社区《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所示。


f6e020b049fc6ee4066380fc1b46dfb4765914f5

Python机器学习数据建模与分析——Numpy和Pandas综合应用案例:空气质量监测数据的预处理和基本分析 本篇文章主要以北京市空气质量监测数据为例子,聚集数据建模中的数据预处理和基本分析环节,说明Numpy和Pandas的数据读取、数据分组、数据重编码、分类汇总等数据加工处理功能。同时在实现案例的过程中对用到的Numpy和Pandas相关函数进行讲解。
异步社区 异步社区(www.epubit.com)是人民邮电出版社旗下IT专业图书旗舰社区,也是国内领先的IT专业图书社区,致力于优质学习内容的出版和分享,实现了纸书电子书的同步上架,于2015年8月上线运营。公众号【异步图书】,每日赠送异步新书。