Write a Python Program to Find the second Largest Number in a Numpy Array. We used the numpy sort function to sort the array in ascending order. Next, we print the value at the last but one index position.
import numpy as np
secLarr = np.array([11, 55, 99, 22, 7, 35, 70])
print("Array Items = ", secLarr)
secLarr.sort()
print("The Second Largest Item in this Array = ", secLarr[len(secLarr) - 2])

This program uses the NumPy module’s partition function to find the second largest distinct value.
NOTE: When you sort an array with duplicate items, the second largest value becomes the largest because both are the same. Similarly, if we use partition(), the result is the same. For example, if we use the list below, the sort () and partition () approaches return 70.
import numpy as np
a = np.array([9, 45, 70, 22, 70, 30])
b = np.partition(a, -2)[-2]
print(b)
70
However, if we apply the NumPy unique() function before partition(), we get the distinct second-largest element in an array.
import numpy as np
a = np.array([9, 45, 70, 22, 70, 30])
b = np.partition(np.unique(a), -2)[-2]
print(b)
45
Python Program to Find Second Largest in an Array using for loop
This Program helps to find the Second Largest in a NumPy Array using the For Loop range. For more examples, refer to the Python Basic Programs.
import numpy as np
secLarr = np.array([15, 22, 75, 99, 35, 70, 120, 60])
print("Items = ", secLarr)
first = second = min(secLarr)
for i in range(len(secLarr)):
if (secLarr[i] > first):
second = first
first = secLarr[i]
elif(secLarr[i] > second and secLarr[i] < first):
second = secLarr[i]
print("The Largest Item = ", first)
print("The Second Largest Item = ", second)
The Second Largest numpy array item using the for loop range output.
Items = [ 15 22 75 99 35 70 120 60]
The Largest Item = 120
The Second Largest Item = 99
This approach is more advanced than the for loop. Here, we use the built-in NumPy max function to find the second-largest array element.
import numpy as np
a = np.array([9, 45, 70, 22, 70, 30])
high = np.max(a)
second_high = np.max(a[a < high])
print(second_high)
45
Also Read