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:

import numpy as np
x = np.array([10,-10,10,-10,-10,10])
y = np.array([.85,.45,.9,.8,.12,.6])
print("Original arrays:")
print(x)
print(y)
result = np.sum((x == 10) & (y > .5))
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

Python Code Editor:

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

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 Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}