Fancy Indexing的用法

237 阅读2分钟

Fancy Indexing

import numpy as np

x = np.arange(16)
x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
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[8]]
[3, 5, 8]

把索引定义成一个列表

ind = [3, 5, 8]

可以直接访问索引

x[ind]
array([3, 5, 8])

不仅可以索引一维数组,还可以索引二维数组

ind = np.array([[0, 2],
                [1, 3]])
x[ind]
array([[0, 2],
       [1, 3]])
X = x.reshape(4, -1)
X
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])
X[row, col]
array([ 1,  6, 11])

取第0行对应col的值

X[0, col]
array([1, 2, 3])

取前两列对应col的值

X[:2,col]
array([[1, 2, 3],
       [5, 6, 7]])

用布尔数组即表示对哪一列感兴趣,

col = [True, False, True, True]
X[:2, col]
array([[1, 2, 3],
       [5, 6, 7]])

numpy,array的比较

x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

判断数组中的元素是否 < 3

x < 3
array([ True,  True,  True, False, False, False, False, False, False,
       False, False, False, False, False, False, False])

判断数组中的元素是否 > 3

x > 3
array([False, False, False, False,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True])

判断数组中的元素是否 = 3

x == 3
array([False, False, False,  True, False, False, False, False, False,
       False, False, False, False, False, False, False])

更复杂的运算,注意2 * x是一个一维数组

2 * x == 24 -4 * x
array([False, False, False, False,  True, False, False, False, False,
       False, False, False, False, False, False, False])

同样适用于二维数组

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]])

比较的意义

np.sum(x<=3)
4
np.count_nonzero(x<=3)
4
np.any(x == 0)
True
np.any(x < 0)
False
np.all(x>=0)
True
np.all(x>0)
False
X
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
np.sum(X % 2 == 0)
8
np.sum(X % 2 == 0,axis = 1)
array([2, 2, 2, 2])
np.sum(X % 2 == 0, axis = 0)
array([4, 0, 4, 0])
np.all(X > 0, axis = 1)
array([False,  True,  True,  True])
x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

注意使用的是位运算符

np.sum((x > 3) & (x < 10))
6
np.sum((x > 3) && (x < 10))
  File "C:\Users\178279~1\AppData\Local\Temp/ipykernel_6464/3416034819.py", line 1
    np.sum((x > 3) && (x < 10))
                    ^
SyntaxError: invalid syntax
np.sum((x % 2 == 0) | (x > 10))
11
np.sum((~(x==0)))
15
x[x < 5]
array([0, 1, 2, 3, 4])
x[x % 2 == 0]
array([ 0,  2,  4,  6,  8, 10, 12, 14])
X[X[:,3] % 3 == 0,:]
array([[ 0,  1,  2,  3],
       [12, 13, 14, 15]])