w3resource

Create array using np.where based on condition in NumPy

NumPy: Universal Functions Exercise-6 with Solution

Using ufuncs with Conditions:

Write a NumPy program that uses the np.where ufunc to create a new array from two existing arrays based on a condition applied to a third array.

Sample Solution:

Python Code:

import numpy as np

# Create three 1D NumPy arrays
array_1 = np.array([1, 2, 3, 4, 5])
array_2 = np.array([10, 20, 30, 40, 50])
condition_array = np.array([True, False, True, False, True])

# Use np.where ufunc to create a new array based on the condition
result_array = np.where(condition_array, array_1, array_2)

# Print the original arrays and the resulting array
print('Array 1:\n', array_1)
print('Array 2:\n', array_2)
print('Condition array:\n', condition_array)
print('Resulting array using np.where:\n', result_array)

Output:

Array 1:
 [1 2 3 4 5]
Array 2:
 [10 20 30 40 50]
Condition array:
 [ True False  True False  True]
Resulting array using np.where:
 [ 1 20  3 40  5]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create Three 1D NumPy Arrays:
    • Created three 1D NumPy arrays: array_1 with values [1, 2, 3, 4, 5], array_2 with values [10, 20, 30, 40, 50], and condition_array with boolean values [True, False, True, False, True].
  • Use np.where ufunc:
    • Use the np.where "ufunc" to create a new array result_array based on the condition applied to condition_array. If the condition is True, the corresponding element from ‘array_1’ is chosen; otherwise, the element from ‘array_2’ is chosen.
  • Print Results:
    • Print the original arrays and the resulting array created using np.where.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Apply np.sin, np.cos, and np.tan ufuncs to angles in NumPy.
Next: Create a custom ufunc in NumPy to compute x^2+2x+1` .

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/create-array-using-np-dot-where-based-on-condition-in-numpy.php