NumPy 使用布爾數(shù)組索引

2021-09-03 17:39 更新

當我們使用(整數(shù))索引數(shù)組索引數(shù)組時,我們提供了要選擇的索引列表。對于布爾索引,方法是不同的;我們明確地選擇數(shù)組中的哪些項是我們想要的,哪些是我們不想要的。

對于布爾索引,人們可以想到的最自然的方法是使用與原始數(shù)組具有相同形狀的布爾數(shù)組:

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

使用布爾值索引的第二種方式更類似于整數(shù)索引;對于數(shù)組的每個維度,我們給出一個一維布爾數(shù)組,選擇我們想要的切片:

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

請注意,一維布爾數(shù)組的長度必須與要切片的維度(或軸)的長度一致。在前面的例子中,b1具有長度為3(的數(shù)目的行中a),和?b2(長度4)適合于索引a的第二軸線(列)?。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號