NumPy 使用布尔数组索引

2021-09-03 17:39 更新

当我们使用(整数)索引数组索引数组时,我们提供了要选择的索引列表。对于布尔索引,方法是不同的;我们明确地选择数组中的哪些项是我们想要的,哪些是我们不想要的。

对于布尔索引,人们可以想到的最自然的方法是使用与原始数组具有相同形状的布尔数组:

  1. >>> a = np.arange(12).reshape(3, 4)
  2. >>> b = a > 4
  3. >>> b # `b` is a boolean with `a`'s shape
  4. array([[False, False, False, False],
  5. [False, True, True, True],
  6. [ True, True, True, True]])
  7. >>> a[b] # 1d array with the selected elements
  8. array([ 5, 6, 7, 8, 9, 10, 11])

这个属性在赋值中非常有用:

  1. >>> a[b] = 0 # All elements of `a` higher than 4 become 0
  2. >>> a
  3. array([[0, 1, 2, 3],
  4. [4, 0, 0, 0],
  5. [0, 0, 0, 0]])

可以查看以下示例来了解如何使用布尔索引生成Mandelbrot 集的图像:

  1. import numpy as np
  2. >>> import matplotlib.pyplot as plt
  3. >>> def mandelbrot(h, w, maxit=20, r=2):
  4. ... """Returns an image of the Mandelbrot fractal of size (h,w)."""
  5. ... x = np.linspace(-2.5, 1.5, 4*h+1)
  6. ... y = np.linspace(-1.5, 1.5, 3*w+1)
  7. ... A, B = np.meshgrid(x, y)
  8. ... C = A + B*1j
  9. ... z = np.zeros_like(C)
  10. ... divtime = maxit + np.zeros(z.shape, dtype=int)
  11. ...
  12. ... for i in range(maxit):
  13. ... z = z**2 + C
  14. ... diverge = abs(z) > r # who is diverging
  15. ... div_now = diverge & (divtime == maxit) # who is diverging now
  16. ... divtime[div_now] = i # note when
  17. ... z[diverge] = r # avoid diverging too much
  18. ...
  19. ... return divtime
  20. >>> plt.imshow(mandelbrot(400, 400))

使用布尔值索引的第二种方式更类似于整数索引;对于数组的每个维度,我们给出一个一维布尔数组,选择我们想要的切片:

  1. >>> a = np.arange(12).reshape(3, 4)
  2. >>> b1 = np.array([False, True, True]) # first dim selection
  3. >>> b2 = np.array([True, False, True, False]) # second dim selection
  4. >>>
  5. >>> a[b1, :] # selecting rows
  6. array([[ 4, 5, 6, 7],
  7. [ 8, 9, 10, 11]])
  8. >>>
  9. >>> a[b1] # same thing
  10. array([[ 4, 5, 6, 7],
  11. [ 8, 9, 10, 11]])
  12. >>>
  13. >>> a[:, b2] # selecting columns
  14. array([[ 0, 2],
  15. [ 4, 6],
  16. [ 8, 10]])
  17. >>>
  18. >>> a[b1, b2] # a weird thing to do
  19. array([ 4, 10])

请注意,一维布尔数组的长度必须与要切片的维度(或轴)的长度一致。在前面的例子中,b1具有长度为3(的数目的行中a),和 b2(长度4)适合于索引a的第二轴线(列) 。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号