Write a Python code to find the second lowest value in each column in a given dataframe

PythonPandasServer Side ProgrammingProgramming

Assume, you have a dataframe and the result for second lowest value in each column as,

Id       2
Salary 30000
Age    23

To solve this, we will follow the steps given below −

Solution

  • Define a dataframe

  • Set df.apply() function inside create lambda function and set the variable like x to access all columns and check expression as

x.sort_values().unique()[1] with axis=0 to return second lowest value as,

result = df.apply(lambda x: x.sort_values().unique()[1], axis=0)

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({'Id':[1,2,3,4,5,6,7,8,9,10],
'Salary':[20000,30000,50000,40000,80000,90000,350000,55000,60000,70000],
            'Age': [22,23,24,25,26,25,26,27,25,24]
      })
print("DataFrame is:\n",df)
print("Second lowest value of each column is:")
result = df.apply(lambda x: x.sort_values().unique()[1], axis=0)
print(result)

Output

DataFrame is:
 Id Salary Age
0 1 20000  22
1 2 30000  23
2 3 50000  24
3 4 40000  25
4 5 80000  26
5 6 90000  25
6 7 350000 26
7 8 55000  27
8 9 60000  25
9 10 70000 24
Second lowest value of each column is:
Id       2
Salary 30000
Age    23
dtype: int64
raja
Published on 12-Feb-2021 10:44:01
Advertisements