w3resource

NumPy: Create two arrays of six element

NumPy: Array Object Exercise-163 with Solution

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’.

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.



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://198.211.115.131/python-exercises/numpy/python-numpy-exercise-163.php