[Python Getting Started Day 52] Python丨NumPy Array Filtering

array filter

Taking some elements from an existing array and creating a new array from it is called filtering.

In NumPy, we use lists of boolean indices to filter arrays.

A boolean indexed list is a list of boolean values ​​corresponding to the indices in the array.

If the value at index is True, the element is included in the filtered array; if the value at index is False, the element is excluded from the filtered array.

example

Create an array with elements at indices 0 and 2, 4:

import numpy as np

arr = np.array([61, 62, 63, 64, 65])

x = [True, False, True, False, True]

newarr = arr[x]

print(newarr)

run instance

The above example will return [61, 63, 65], why?

The indices are 0 and 2,4 in this case because the new filter contains only values ​​where the filter array has the value True.

Create an array of filters

In the example above, we hardcoded the True and False values, but a common use would be to create an array of filters based on conditions.

example

Create a filter array that only returns values ​​greater than 62:

import numpy as np

arr = np.array([61, 62, 63, 64, 65])

# 创建一个空列表
filter_arr = []

# 遍历 arr 中的每个元素
for element in arr:
  # 如果元素大于 62,则将值设置为 True,否则为 False:
  if element > 62:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

run instance

example

Create a filter array that returns only even elements in the original array:

import numpy as np

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

# 创建一个空列表
filter_arr = []

# 遍历 arr 中的每个元素
for element in arr:
  # 如果元素可以被 2 整除,则将值设置为 True,否则设置为 False
  if element % 2 == 0:
    filter_arr.append(True)
  else:
    filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

run instance

Create filters directly from arrays

The above example is a very common task in NumPy, and NumPy provides a nice way to solve it.

We can directly replace the array instead of the iterable variable in the condition and it will work as we expect.

example

Create a filter array that only returns values ​​greater than 62:

import numpy as np

arr = np.array([61, 62, 63, 64, 65])

filter_arr = arr > 62

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

run instance

example

Create a filter array that returns only even elements in the original array:

import numpy as np

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

filter_arr = arr % 2 == 0

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

run instance

Guess you like

Origin blog.csdn.net/ooowwq/article/details/129826370
Recommended