Numpy array数组的操作

版权声明:本博客内容归个人所有,如需转载,请标明出处。 https://blog.csdn.net/m0_37468171/article/details/89845040

布尔索引

# 创建一个随机整数数组
arr2 = np.random.randint(0,50,20)
# 打印结果
array([17, 42, 35,  3, 38,  1, 34, 12, 24, 39, 30, 33, 46,  0, 30,  0, 32,
       28, 16,  0])

# 获取布尔索引
arr2%2 == 0
# 打印结果
array([False,  True, False, False,  True, False,  True,  True,  True,
       False,  True, False,  True,  True,  True,  True,  True,  True,
        True,  True])

# 通过布尔索引获取需要的元素数组
arr2[arr2%2 ==0] 
array([42, 38, 34, 12, 24, 30, 46,  0, 30,  0, 32, 28, 16,  0])
对比列表list,如下:
m = [1,2,3,5]
m%2==0

输出结果:
TypeError                                 Traceback (most recent call last)
<ipython-input-58-738d9db1a292> in <module>
      1 m = [1,2,3,5]
----> 2 m%2==0

TypeError: unsupported operand type(s) for %: 'list' and 'int'
总结,列表是不支持“布尔索引”的,而numpy 中的 array 是支持“布尔索引的”

数组形式的索引

# 创建数组
arr3 = np.array([0,1,2,0,3,4,0,5,6,0])
# 得到一个下标数组
indexs = np.nonzero(arr3)
indexs
# 输出结果
(array([1, 2, 4, 5, 7, 8]),)
# 根据索引数组获取元素
arr3[indexs]
array([1, 2, 3, 4, 5, 6])

对比列表list,如下:
#创建一个列表
list1 = [1,2,3,4,5]

# 根据索引数组获取元素
list1[1,2,4]

#输出结果:
TypeError                                 Traceback (most recent call last)
<ipython-input-63-8fa735770a63> in <module>
      1 list1 = [1,2,3,4,5]
----> 2 list1[[1,2,3]]

TypeError: list indices must be integers or slices, not list
总结,列表是不支持“数组索引”的,而numpy 中的 array 是支持“数组索引的”

猜你喜欢

转载自blog.csdn.net/m0_37468171/article/details/89845040