Numpy Where Function

N

Numpy Where Function

The numpy.where function is a powerful tool in the Numpy library that allows for efficient and concise conditional array operations. It can be used to selectively apply operations based on specified conditions, returning elements from either an input array or two other arrays, depending on the condition being met.

numpy.where()Syntax and Parameters

The syntax for the numpy.where function is as follows:

np.where(condition, x, y) 
  • condition: This is the condition that needs to be met for the function to apply the x values.
  • x: This is the value to place in the output array where the condition is True.
  • y: This is the value to place where the condition is False.

Examples of numpy.where()

Let’s explore a few examples to understand how the numpy.where function works:

Example 1

import numpy as np

arr = np.array([3, 6, 9, 12, 15])
result = np.where(arr % 2 == 0, 'numpy', 'where')
print(result)

Output:

Numpy Where Function

Example 2

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
result = np.where(arr < 3, arr*2, arr/2)
print(result)

Output:

Numpy Where Function

Example 3

import numpy as np

arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([10, 20, 30, 40, 50])

result = np.where(arr1 > 2, arr1, arr2)
print(result)

Output:

Numpy Where Function

Example 4

import numpy as np

arr = np.array([[1, 2], [3, 4]])
result = np.where(arr < 3, arr*2, arr/2)
print(result)

Output:

Numpy Where Function

Example 5

import numpy as np

arr = np.array([8, 6, 4, 2, 0])
result = np.where(arr == 0, 1, 1/arr)
print(result)

Output:

Numpy Where Function

Example 6

import numpy as np

arr = np.array([1, -2, 3, -4, 5])
result = np.where(arr < 0, arr*-1, arr)
print(result)

Output:

Numpy Where Function

Example 7

import numpy as np

arr = np.array([90, 60, 30, 0, -30])
result = np.where(arr < 0, 'negative', np.where(arr == 0, 'zero', 'positive'))
print(result)

Output:

Numpy Where Function

Example 8

import numpy as np

arr = np.array([10, 15, 20, 25, 30])
result = np.where(arr < 20, arr*2, np.where(arr > 25, arr/2, arr))
print(result)

Output:

Numpy Where Function

Example 9

import numpy as np

arr1 = np.array([1, 0, 1, 0])
arr2 = np.array([10, 20, 30, 40])
result = np.where(arr1 == 1, arr2, 0)
print(result)

Output:

Numpy Where Function

Example 10

import numpy as np

arr = np.array([[1, 2], [3, 4]])
result = np.where(arr % 2 == 0, 'numpy', 'where')
print(result)

Output:

Numpy Where Function

Conclusion of numpy.where() Function

These 10 examples demonstrate the versatility and utility of the numpy.where function in efficiently performing conditional operations on arrays. By leveraging this function, you can streamline your code and achieve the desired outcomes with ease.

Latest Articles

Popular Articles