如何在Python中使用NumPy where()的多个条件

如何在Python中使用NumPy where()的多个条件

在Python中,NumPy有许多创建数组的库函数,where是其中之一,用于从另一个数组的满足条件创建一个数组。 numpy.where()函数返回一个输入数组中满足给定条件的元素的索引。

语法:

numpy.where(condition[, x, y])

参数:

  • condition : 当真时,产生x,否则产生y。
  • x, y :x、y和条件需要可以广播到一些形状。

返回: [ndarray or tuple of ndarrays] 如果同时指定了x和y,输出数组包含条件为True的x的元素,以及其他地方的y的元素。_

如果只给出了条件,则返回tuple condition.nonzero(),即条件为True的索引。在上面的语法中,我们可以看到where()函数可以接受两个参数,其中一个是必须的,另一个是可选的。如果条件的值为 “真”,将根据索引创建一个数组。

示例 1:

Numpy where()的多个条件使用逻辑OR。

# Import NumPy library
  
import numpy as np
  
# Create an array using the list
  
np_arr1 = np.array([23, 11, 45, 43, 60, 18, 
                    33, 71, 52, 38])
print("The values of the input array :\n", np_arr1)
  
  
# Create another array based on the 
# multiple conditions and one array
new_arr1 = np.where((np_arr1))
  
# Print the new array
print("The filtered values of the array :\n", new_arr1)
  
# Create an array using range values
np_arr2 = np.arange(40, 50)
  
# Create another array based on the 
# multiple conditions and two arrays
new_arr2 = np.where((np_arr1), np_arr1, np_arr2)
  
# Print the new array
print("The filtered values of the array :\n", new_arr2)

输出:

如何在Python中使用NumPy where()的多个条件?

示例 2:

Numpy where()的多个条件使用逻辑AND。

# Import NumPy library
  
import numpy as np
  
# Create two arrays of random values
np_arr1 = np.random.rand(10)*100
np_arr2 = np.random.rand(10)*100
  
  
# Print the array values
print("\nThe values of the first array :\n", np_arr1)
print("\nThe values of the second array :\n", np_arr2)
  
  
# Create a new array based on the conditions
new_arr = np.where((np_arr1), np_arr1, np_arr2)
  
# Print the new array
print("\nThe filtered values of both arrays :\n", new_arr)

输出:

如何在Python中使用NumPy where()的多个条件?

示例 3:

Numpy where()在多维数组中具有多个条件。

# Import NumPy library
  
import numpy as np
  
# Create two multidimensional arrays of 
# integer values
np_arr1 = np.array([[6, 13, 22, 7, 12],  
                    [7, 11, 16, 32, 9]])
np_arr2 = np.array([[44, 20, 8, 35, 10],  
                    [98, 23, 42, 6, 13]])
  
# Print the array values
print("\nThe values of the first array :\n", np_arr1)
print("\nThe values of the second array :\n", np_arr2)
  
# Create a new array from two arrays based on
# the conditions
new_arr = np.where(((np_arr1 % 2 == 0) & (np_arr2 % 2 == 1)), 
                   np_arr1, np_arr2)
  
# Print the new array
print("\nThe filtered values of both arrays :\n", new_arr)

输出:

如何在Python中使用NumPy where()的多个条件?

总结:

NumPy中的where()函数用于从现有的数组中创建一个具有多个条件数的新数组。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程