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

# 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)]
print("\nSecond-largest value in each column:")
print(second_largest_values)
``````

Sample 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)]: 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), 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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Decapitalizes the first letter of a string:

Example:

```def tips_decapitalize(s, upper_rest=False):
return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])
print(tips_decapitalize('PythonTips'))
print(tips_decapitalize('PythonTips', True))
```

Output:

```pythonTips
pYTHONTIPS
```

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook