标签:
布尔型索引
1 #!/usr/bin/env python 2 #-*-coding:utf-8-*- 3 ‘‘‘ 4 Description:初学numpy(三)--布尔型索引 5 Created on 2015年10月8日 6 @author: zenwan 7 @version: 8 ‘‘‘ 9 import numpy as np 10 from pprint import pprint 11 12 names = np.array([‘beijing‘,‘anhui‘,‘shanghai‘,‘jiangsu‘,‘zhejiang‘,‘shanghai‘,‘anhui‘])#有重复 13 data = np.random.randn(7,4)#生成正态分布的随机数 14 pprint(names) 15 pprint(data) 16 17 ‘‘‘ 18 假设names中的每个名字对应data数组中的一行,而我们想要选出对应于名字‘shanghai‘的所有行。 19 我们想要选出对应于‘shanghai‘的所有数据行. 20 跟算术运算一样,数组的比较运算(如==)也是矢量化的,因此数组names和字符串‘shanghai‘比较运算会产生一个布尔型数组arr_bool, 21 这个布尔型数组可以用于素组索引 22 ‘‘‘ 23 arr0_bool = (names == ‘shanghai‘)#数组跟字符串比较运算会产生一个布尔型的数组 24 pprint (arr0_bool) #array([False, False, True, False, False, True, False], dtype=bool) 25 pprint (data[arr0_bool]) 26 27 #将布尔型数组跟切片、整数、整数序列等混合使用 28 pprint(data[names == ‘shanghai‘,2:]) 29 pprint(data[names == ‘shanghai‘,3]) 30 31 #选择‘shanghai‘以外的其它值等其它组合 32 arr1_bool =(names != ‘shanghai‘) 33 arr2_bool =((names != ‘shanghai‘)|(names==‘jiangsu‘)) 34 arr2_bool =((names != ‘shanghai‘)&(names==‘jiangsu‘)) 35 36 #将data中所有的正数设为-1 37 data[data > 0] = -1#数组的比较运算是矢量化的 38 pprint (data) 39 40 #通过一维布尔型数组设置证行或者列,如将‘shanghai‘的所对应的整行数据设置为0 41 data [names ==‘shanghai‘] = 0 42 pprint(data)
运行结果:
1 array([‘beijing‘, ‘anhui‘, ‘shanghai‘, ‘jiangsu‘, ‘zhejiang‘, ‘shanghai‘, 2 ‘anhui‘], 3 dtype=‘|S8‘) 4 array([[ 0.84608482, 0.51050985, -0.43504218, -1.08530829], 5 [ 0.51865817, -1.0914367 , -0.6953841 , -1.59947846], 6 [-0.9308739 , -0.2748063 , -0.410821 , -1.66078485], 7 [ 0.2290689 , -0.85357479, -0.42896687, 0.97397006], 8 [-0.60247776, -0.24399895, -1.03297297, -0.76709796], 9 [-0.31226921, -0.42020231, 1.12008391, 0.54366616], 10 [ 0.53271514, 0.50497622, 1.02203728, -0.12969158]]) 11 array([False, False, True, False, False, True, False], dtype=bool) 12 array([[-0.9308739 , -0.2748063 , -0.410821 , -1.66078485], 13 [-0.31226921, -0.42020231, 1.12008391, 0.54366616]]) 14 array([[-0.410821 , -1.66078485], 15 [ 1.12008391, 0.54366616]]) 16 array([-1.66078485, 0.54366616]) 17 array([[-1. , -1. , -0.43504218, -1.08530829], 18 [-1. , -1.0914367 , -0.6953841 , -1.59947846], 19 [-0.9308739 , -0.2748063 , -0.410821 , -1.66078485], 20 [-1. , -0.85357479, -0.42896687, -1. ], 21 [-0.60247776, -0.24399895, -1.03297297, -0.76709796], 22 [-0.31226921, -0.42020231, -1. , -1. ], 23 [-1. , -1. , -1. , -0.12969158]]) 24 array([[-1. , -1. , -0.43504218, -1.08530829], 25 [-1. , -1.0914367 , -0.6953841 , -1.59947846], 26 [ 0. , 0. , 0. , 0. ], 27 [-1. , -0.85357479, -0.42896687, -1. ], 28 [-0.60247776, -0.24399895, -1.03297297, -0.76709796], 29 [ 0. , 0. , 0. , 0. ], 30 [-1. , -1. , -1. , -0.12969158]])
标签:
原文地址:http://www.cnblogs.com/zenzen/p/4861228.html