w3resource

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

NumPy: Advanced Exercise-11 with Solution

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

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 second-largest value in each row
second_largest = np.partition(nums, -2, axis=1)[:, -2]
print("\nSecond-largest value in each row:")
print(second_largest)

Sample Output:

Original array elements:
[[0.82671119 0.28189079 0.37220477 0.89521426 0.92550788]
 [0.56434694 0.94849553 0.70116302 0.77298376 0.37783512]
 [0.83622642 0.16947668 0.71134028 0.2114369  0.71333448]
 [0.74094415 0.02245679 0.10639303 0.40430979 0.01500681]
 [0.16620753 0.85257244 0.3696228  0.31196318 0.413779  ]]

Second-largest value in each row:
[0.89521426 0.77298376 0.71333448 0.40430979 0.413779  ]

Explanation:

In the above exercise -

nums = np.random.rand(5, 5): This line creates a 5x5 NumPy array with random values between 0 and 1 using the rand method of the numpy.random module.

second_largest = np.partition(nums, -2, axis=1)[:, -2]: This line finds the second-largest value in each row of the 'nums' 'array'.

The np.partition method performs an in-place partial sort of the array along the given axis (axis=1, i.e. row-wise). The -2 argument specifies that we want to partition the array such that the second largest value is in the second-to-last position (the last position being the largest value).

The [:, -2] indexing syntax extracts the second-to-last element from each row of the partially sorted array. The resulting second_largest array contains the second-largest value in each row of the original ‘nums’ array.

Python-Numpy Code Editor:

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

Previous: Create a 5x5 array with random values and sort each column.
Next: Find the second-largest value in each column in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.