NumPy: Create two arrays of six element
Count instances of values based on conditions.
Create two arrays of six elements. Write a NumPy program to count the number of instances of a value occurring in one array on the condition of another array.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating two NumPy arrays
x = np.array([10, -10, 10, -10, -10, 10])
y = np.array([.85, .45, .9, .8, .12, .6])
# Displaying the original arrays
print("Original arrays:")
print(x)
print(y)
# Counting the number of instances where x equals 10 and y is greater than 0.5
result = np.sum((x == 10) & (y > 0.5))
# Printing the count of instances based on the conditions specified
print("\nNumber of instances of a value occurring in one array on the condition of another array:")
print(result)
Sample Output:
Original arrays: [ 10 -10 10 -10 -10 10] [0.85 0.45 0.9 0.8 0.12 0.6 ] Number of instances of a value occurring in one array on the condition of another array: 3
Explanation:
x = np.array([10,-10,10,-10,-10,10]): Create a NumPy array x with the elements [10, -10, 10, -10, -10, 10].
y = np.array([.85,.45,.9,.8,.12,.6]): Create another NumPy array y with the elements [0.85, 0.45, 0.9, 0.8, 0.12, 0.6].
result = np.sum((x == 10) & (y > .5)): Create a boolean mask that checks two conditions:
- Elements in array x are equal to 10.
- Corresponding elements in array y are greater than 0.5.
The result is a boolean array with the same shape as the input arrays. Here np.sum() function is used to count the number of True values in the boolean array (i.e., the number of elements that meet both conditions).
Finally print() function prints the value of ‘result’.
For more Practice: Solve these Related Problems:
- Write a NumPy program to count occurrences of a specified value in one array, conditioned on corresponding values in a second array exceeding a threshold.
- Create a function that uses boolean masking on two arrays to count instances where one array’s element meets a criterion and the corresponding element in another array meets another.
- Implement a solution using np.logical_and to combine conditions across two arrays and then count true instances.
- Test the conditional counting on arrays with mixed positive and negative values to validate the approach.
Python-Numpy Code Editor:
Previous: Write a NumPy program to select from the first axis (K) by the indices tidx to get an array of shape (J=4, I=8) back.Next: Write a NumPy program to save as text a matrix which has in each row 2 float and 1 string at the end.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics