Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Provide name of value with largest speed

I am trying to write a python script which reads in a csv file and then prints out the column value with the largest speed.

The CSV is formatted as such:

name, cartype, speed
vauxall, car, 99.0mph
bugati, bike, 120.0mph
mercedes, car, 134.0mph

I would expect my script to print out:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mercedes

This is what I have so far:

import pandas as pd

df=pd.read_csv('cars.csv')

row_with_max_speed = df.loc[df["speed"].idxmax()]

print(f"{row_with_max_speed.name}")

I think I am having an issue with speed due to the values having "mph" within them

>Solution :

You can extract the numeric part of speed and convert it to float before calculating idxmax:

df.loc[df["speed"].str[:-3].astype(float).idxmax(), "name"]

Output:

mercedes

UPD: changed apply to astype to support None values in speed column

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading