+2 votes
in Programming Languages by (15.3k points)
edited by
I have a DataFrame with Name, Age, and Income as columns. I want to find persons with max and min age. Which function should I use to find the maximum and minimum values?

1 Answer

0 votes
by (26.1k points)

You can try one of the following approaches to find min and max values in a column of a Pandas dataframe:

Approach 1

>>> import pandas as pd
>>> df1 = pd.DataFrame({'Name':['abc','def','ghi','jkl'], 'Age':[42,23,12,60], 'income':[1200,200,3000,2800]})
>>> df1
  Name  Age  income
0  abc   42    1200
1  def   23     200
2  ghi   12    3000
3  jkl   60    2800
>>> df1[df1['Age']==df1['Age'].max()]
  Name  Age  income
3  jkl   60    2800
>>> df1[df1['Age']==df1['Age'].min()]
  Name  Age  income
2  ghi   12    3000
 

Approach 2

>>> df1.sort_values(['Age'], ascending=False).head(1)
  Name  Age  income
3  jkl   60    2800
>>> df1.sort_values(['Age'], ascending=True).head(1)
  Name  Age  income
2  ghi   12    3000

...