NumPy is an essential library in Python for numerical computations. It allows you to work with large multi-dimensional arrays and matrices, making it the go-to tool for data manipulation and scientific computing. One of the powerful features of NumPy is the ability to write conditional expressions that can filter or manipulate data based on specific conditions.
In this blog post, we’ll explore how to write conditional expressions using NumPy with simple examples, making it easier for you to handle array data efficiently.
What Are Conditional Expressions?
Conditional expressions allow you to apply a condition to each element in a NumPy array. Based on the result of this condition, you can either return one value or another. The most common method for writing conditional expressions in NumPy is by using the np.where() function.
The syntax for np.where() is:
np.where(condition, value_if_true, value_if_false)
condition: The condition to check for each element in the array.
value_if_true: The value to return if the condition is True.
value_if_false: The value to return if the condition is False.
import numpy as np
# Array of student scores
scores = np.array([35, 60, 45, 80, 50])
# Conditional check: Pass if score >= 50, otherwise Fail
result = np.where(scores >= 50, 'Pass', 'Fail')
print("Scores:", scores)
print("Result:", result)
#output
Scores: [35 60 45 80 50]
Result: ['Fail' 'Pass' 'Fail' 'Pass' 'Pass']
In this example:
The condition checks if each score is greater than or equal to 50.
- If the score meets the condition, the result is “Pass”.
- If the score does not meet the condition, the result is “Fail”
Example 2: Replacing Values Based on Condition
Conditional expressions can also be used to modify the values of an array based on a condition. Let’s consider an example where we replace all values less than 50 with the average score
# Calculate the average score
average_score = scores.mean()
# Replace scores less than 50 with the average score
adjusted_scores = np.where(scores < 50, average_score, scores)
print("Original Scores:", scores)
print("Adjusted Scores:", adjusted_scores)
#output
Original Scores: [35 60 45 80 50]
Adjusted Scores: [55. 60. 55. 80. 50.
In this case:
- We use np.where() to check for scores less than 50 and replace them with the average score (55).
- Scores that are already greater than or equal to 50 remain unchanged.
Top comments (0)