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

2021-09-03 17:39 更新

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

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

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

這個(gè)屬性在賦值中非常有用:

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

可以查看以下示例來了解如何使用布爾索引生成Mandelbrot 集的圖像:

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

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

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

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

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)