简体   繁体   中英

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.

使用idxmax

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM