Numpy数组切片、bool索引、掩码和花哨索引

Numpy数组切片、bool索引、掩码和花哨索引

数组切片(slice)

数组切片的公式为 my_array[start: end: step, start: end: step]

#示例1:
import numpy as np
#设置随机种子
np.random.seed(0)
#初始化一个维度为3x4的数组
a = np.random.randint(0,10,(3,4))
#取出a数组前2行和前2列组成的数组
print(a)
print(a[0:2:1, 0:2:1])


#输出如下
[[5 0 3 3]
 [7 9 3 5]
 [2 4 7 6]]
[[5 0]
 [7 9]]
#可以看到,对a取切片结果直观上就是取出数组中的一部分

在实际应用中,根据需要可以对r_start: r_stop: r_step句式进行简化,列的切片索引也是一样

依然以数组a作为演示:

简化操作 等价的完整操作
: : -1 end: 0: -1,表示反向遍历
: 0: end: 1,表示正向遍历
: a 0: a: 1,表示取该轴上的前a个元素
#行倒序排列并且取所有的列
print(a[::-1,:])
#与数组元素索引一起使用,取第一行并且取前2列
print(a[1,:2])

#输出如下:
[[2 4 7 6]
 [7 9 3 5]
 [5 0 3 3]]
[7 9]

bool索引(bool indexing)

Numpy的通用函数可以用来替换循环,以快速实现数组的逐元素(element-wise)运算,同样,我们也可以通过其他通用函数实现数组的逐元素比较,这些用于用于比较的通用函数可以用运算符等价。

运算符 对应的通用函数
== np.equal
!= np.not_equal
< np.less
<= np.less_equal
> np.greater
>= np.greater_equal
In [43]: x= np.arange(10)

In [44]: x<5 #小于
Out[44]: 
array([ True,  True,  True,  True,  True, False, False, False, False,
       False])

In [45]: x>5 #大于
Out[45]: 
array([False, False, False, False, False, False,  True,  True,  True,
        True])

In [46]: x <= 3 #小于等于
Out[46]: 
array([ True,  True,  True,  True, False, False, False, False, False,
       False])

In [48]: x >=4  #大于等于
Out[48]: 
array([False, False, False, False,  True,  True,  True,  True,  True,
        True])

In [49]: x != 9
Out[49]: 
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
       False])

In [50]: x ==4 
Out[50]: 
array([False, False, False, False,  True, False, False, False, False,
       False])

掩码(mask)

通过将bool索引作为参数传给数组(bool索引和数组同型),返回一个所有bool索引为True的子数组(一维)

np.random.seed(0)
x = np.random.randint(0,10,(3,4))
bool_index = x < 5
print(x)
print(x[bool_index])

#输出如下
[[5 0 3 3]
 [7 9 3 5]
 [2 4 7 6]]
[0 3 3 3 2 4]

花哨索引(fancy indexing)

花哨索引和前面的简单索引非常相似,但是传递的是索引数组,而不是单个标量。花哨索引让我们能够快速获得并修改复杂的数组值的子数据集。

花哨索引在概念上非常简单,它意味着传递一个索引数组来一次性获得某个维度上的多个数组元素,例如以下数组:

#获得一维数组上的多个元素
c = np.arange(10)
fancy_index = [1,6,8]
print(c)
print(c[fancy_index])

#结果如下:
[0 1 2 3 4 5 6 7 8 9]
[1 6 8]
#获取二维数组上多个元素
np.random.seed(0)
d = np.random.randint(0,10,(3,4))
print(d)
print(d[[1,2,1],[2,2,0]])

#结果如下:
[[5 0 3 3]
 [7 9 3 5]
 [2 4 7 6]]

[3 7 7]
#这里的花哨索引分别取到了d[1,2]、d[3,2]、d[1,0]
#可以将不同维度上的花哨索引组合起来使用
np.random.seed(0)
d = np.random.randint(0,10,(3,4))
print(d)
#对数组d分别取出行1,行0,行2并按此顺序组合,接着对组合出来的新数组,分别取出列2,列1,列3并按此顺序重新组合
print(d[[1,0,2]][:,[2,1,3]])

结果如下:
[[5 0 3 3]
 [7 9 3 5]
 [2 4 7 6]]

[[3 9 5]
 [3 0 3]
 [7 4 6]]

猜你喜欢

转载自blog.csdn.net/jasonzhoujx/article/details/81607834
今日推荐