# 导包 import numpy as np
Fancy Indexing 应用在一维数组
x = np.arange(16) x[3] # 3 x[3:9] # array([3, 4, 5, 6, 7, 8]) x[3:9:2] # array([3, 5, 7]) [x[3], x[5], x[7]] # [3, 5, 7] ind = [3, 5, 7] x[ind] # array([3, 5, 7]) ind = np.array([[0, 2], [1, 3]]) x[ind] """ array([[0, 2], [1, 3]]) """
Fancy Indexing 应用在二维数组
X = x.reshape(4, -1) """ array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) """ row = np.array([0, 1, 2]) col = np.array([1, 2, 3]) # 1行2列,2行3列,3行4列 X[row, col] # array([ 1, 6, 11]) # 前2行 2,3,4列 X[:2, col] """ array([[1, 2, 3], [5, 6, 7]]) """ col = [True, False, True, True] X[0, col] # array([0, 2, 3])
numpy.array 的比较
返回布尔值
x # array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) x < 3 """ array([ True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False]) """ x >= 3 x == 3 x != 3 # 计算公式也可以接受 2 * x == 24 - 4 * x X """ array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) """ X < 6 """ array([[ True, True, True, True], [ True, True, False, False], [False, False, False, False], [False, False, False, False]]) """
使用 numpy.array 的比较结果
# x <= 3 的个数 np.count_nonzero( x <= 3) # x <= 3 的个数 np.sum(x <= 3) # 每列能整除2的个数 np.sum(X % 2 == 0, axis=0) # array([4, 0, 4, 0]) # 每行能整除2的个数 np.sum(X % 2 == 0, axis=1) # array([2, 2, 2, 2]) #只要有任何一个值为 0,返回就是 true np.any(x == 0) #所有值都 > 0,返回就是 true np.all(x > 0) # 每行的值都 > 0 , 返回True np.all(X > 0, axis=1) # array([False, True, True, True]) # (3,10)范围内的数 np.sum((x > 3) & (x < 10)) # 整除2,或者 > 10的个数 np.sum((x % 2 == 0) | (x > 10)) # 非0个数 np.sum(~(x == 0))
比较结果和 Fancy Indexing
x % 2 == 0 """ array([ True, False, True, False, True, False, True, False, True, False, True, False, True, False, True, False]) """ x[x % 2 == 0] # array([ 0, 2, 4, 6, 8, 10, 12, 14]) x[x < 5] # 取第4列数据,取余为0为True的索引为行索引,取1、4行,所有列数据 X[X[:,3] % 3 == 0, :]