w3resource

Advanced NumPy Exercises - Find the second-largest value in each column in an array

NumPy: Advanced Exercise-12 with Solution

Write a NumPy program to create a 5x5 array with random values and find the second-largest value in each column.

Sample Solution:

Python Code:

import numpy as np
# create a 5x5 array with random values
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
# find the indices of the second-largest value in each column
indices = np.argsort(nums, axis=0)[-2, :]
# get the second-largest value in each column using the indices
second_largest_values = nums[indices, np.arange(nums.shape[1])]
print("\nSecond-largest value in each column:")
print(second_largest_values)

Output:

Original array elements:
[[0.43548628 0.56830303 0.35266475 0.08104804 0.42066255]
 [0.32249988 0.99106993 0.29643649 0.24686359 0.33177455]
 [0.82353428 0.29085088 0.78221062 0.12124152 0.00793634]
 [0.06281302 0.39830301 0.13914671 0.26938172 0.80440981]
 [0.79197112 0.61384451 0.27912583 0.50680852 0.35902385]]

Second-largest value in each column:
[0.79197112 0.61384451 0.35266475 0.26938172 0.42066255]

Explanation:

In the above exercise -

nums = np.random.rand(5, 5): This line creates a 5x5 NumPy array filled with random numbers between 0 and 1.

indices = np.argsort(nums, axis=0)[-2, :]: This line sorts the nums array along the first axis (i.e., vertically) and returns the indices of the sorted elements. The -2 index in [-2, :] selects the second-largest element, and the : in [-2, :] means to select all columns. The resulting array indices contains the row indices of the second-largest values for each column.

second_largest_values = nums[indices, np.arange(nums.shape[1])]: This line creates a new array second_largest_values by indexing nums using the row indices in indices and column indices created by np.arange(nums.shape[1]), which returns an array of integers from 0 to the number of columns in nums. This selects the second-largest value in each column and creates a 1D array containing those values.

Python-Numpy Code Editor:

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

Previous: Find the second-largest value in each row in an array.
Next: Replace the maximum value with 0 in a 5x5 array with random values.

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/advanced-numpy-exercise-12.php