w3resource

NumPy: Find the position of the index of a specified value greater than existing value in NumPy array

NumPy: Array Object Exercise-118 with Solution

Write a NumPy program to find the position of the index of a specified value ranked higher than an existing value in a NumPy array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Assigning a value of 4 to the variable 'n'
n = 4

# Creating a NumPy array 'nums' containing integers from -6 to 5 (inclusive)
nums = np.arange(-6, 6)

# Printing a message indicating the original array will be displayed
print("\nOriginal array:")

# Printing the original array 'nums'
print(nums)

# Printing a message indicating the position of the index based on the condition 'nums > n/2'
print("\nPosition of the index:")

# Finding the index position of the maximum value that satisfies the condition 'nums > n/2'
print(np.argmax(nums > n/2))

Sample Output:

Original array:
[-6 -5 -4 -3 -2 -1  0  1  2  3  4  5]

Position of the index:
9

Explanation:

In the above code -

n= 4: Set the value of n to 4.

nums = np.arange(-6, 6): This line creates a NumPy array named nums containing integers from -6 to 5 using the np.arange() function.

np.argmax(nums>n/2): Check which elements of the nums array are greater than half of n (which is 4/2 = 2). This creates a boolean array, with True values where the condition is met (nums > 2) and False values elsewhere. The np.argmax() function returns the index of the first True value, i.e., the first element greater than 2 in the nums array.

Finally print() function prints the result. In this case, it will output the index 9.

Pictorial Presentation-1:

Python NumPy: Find the position of the index of a specified value greater than existing value in NumPy array

Pictorial Presentation-2:

Python NumPy: Find the position of the index of a specified value greater than existing value in NumPy array

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute the line graph of a set of data.
Next: Write a NumPy program to add a new row to an empty NumPy array.

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-118.php