Knot
Knot

Reputation: 141

Pandas corresponding column values when using min

I am having a dictionary-like below. I want to find the minimum by age and need to find the corresponding first name and last name of it.

 [ {
    "firstname": "abc",
    "lastname": "xyz",
    "date": "2020-05-16"
    "age": 15
    }]

Code

df= pd.DataFrame(dict)

for date, df_grp in df.groupby(['date']):
   min = df_grp['age'].min()
   firstName = ""
   lastName = ""

I am not sure how can I get the corresponding first name and last name of min value. In this case "abc" and "xyz".

Upvotes: 0

Views: 702

Answers (1)

Worley
Worley

Reputation: 41

Assuming you don't have duplicate ages you can use argmin() to return the index of the minimum value.

idx_min = df_grp['age'].argmin()
firstName = df_grp['firstname'][idx_min]
lastName = df_grp['lastname'][idx_min]

If instead you need to get a list of indices for each individual with the minimum age you can find the minimum age and use the numpy function argwhere().

min = df_grp['age'].min()
idx_list = np.argwhere(df_grp['age']==min_val)

This will return a list that contains the index for each row containing a person with the minimum age. You can loop through that list to extract the names according to your needs.

Upvotes: 2

Related Questions