Python NumPy(十二)过滤器数组

过滤数组

从现有数组中取出一些元素并从中创建一个新数组称为过滤

在 NumPy 中,您使用布尔索引列表过滤数组

布尔索引列表是与数组中的索引对应的布尔值列表

如果索引处的值是True该元素,则该元素包含在过滤后的数组中,如果该索引处的值是 False该元素,则从过滤后的数组中排除。

例子

从索引 0 和 2 上的元素创建一个数组:

import numpy as np

arr = np.array([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x]
print(newarr)
======
[41 43]

创建过滤器数组

True 在上面的示例中,我们对and值进行了硬编码False,但常见的用途是根据条件创建一个过滤器数组。

例子

创建一个过滤器数组,它只返回大于 42 的值:

import numpy as np

arr = np.array([41, 42, 43, 44])

# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
  # if the element is higher than 42, set the value to True, otherwise False:
  if element > 42:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

例子

创建一个过滤器数组,它只返回原始数组中的偶数元素:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

# Create an empty list
filter_arr = []

# go through each element in arr
for element in arr:
  # if the element is completely divisble by 2, set the value to True, otherwise False
  if element % 2 == 0:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

直接从数组创建过滤器

上面的例子是 NumPy 中相当常见的任务,NumPy 提供了一种很好的方法来解决它。

我们可以在我们的条件中直接替换数组而不是可迭代变量,它会像我们期望的那样工作。

例子

创建一个过滤器数组,它只返回大于 42 的值:

import numpy as np

arr = np.array([41, 42, 43, 44])

filter_arr = arr 42

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)
转载与:

posted on 2022-03-28 21:30  -G  阅读(359)  评论(0)    收藏  举报

导航