Technosonic
Technosonic

Reputation: 29

Extract value based on max value - pandas dataframe

I am trying to extract a value ('location') based on the highest value in another column ('total_cases') and assign it to highest_no_new

My previous dataframe where I want to extract the value from is called no_new_cases

I want to pick out the 'location' with the highest number of 'total_cases' from no_new_cases

I am able to access the highest number of 'total_cases', but not the location:

highest_no_new = no_new_cases['total_cases'].max()

Please can you help return the 'location'?

Thanks in advance.

Upvotes: 1

Views: 439

Answers (2)

Grayrigel
Grayrigel

Reputation: 3594

You can use iloc method:

df['highest_no_new'] = df.iloc[df.total_cases.argmax()]['location']

Example:

>>> d = {'location': [1, 2], 'total_cases': [3, 4]}
>>> df = pd.DataFrame(d)
>>> df
   location  total_cases
0         1            3
1         2            4

>>> df.iloc[df.total_cases.argmax()]['location']
2

Upvotes: 1

Scott Boston
Scott Boston

Reputation: 153460

Use idxmax:

df.loc[df['total_cases'].idxmax(), 'location']

Upvotes: 2

Related Questions