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

How to convert an object that is a fraction to an integer in python

ValueError: invalid literal for int() with base 10: ‘100/100’

my data set has a rating column that holds a rating in the form of an object presented as: 98/100, 99/100, 60/100 ect…

I need to convert this column to an int such as: 98, 99, 60 ect

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

I tried .astype and int(float())

>Solution :

Taking into account that:

  1. You are talking about pandas dataframes
  2. Each grade is in the form X/100, if not – then a basic computation can be done in the lambda function below.

you can use the apply method and then use the astype to convert the column to integer values:

df = df['rating'].apply(lambda x: x.split('/')[0]).astype(int))

import pandas as pd
df = pd.DataFrame.from_dict({'rating': ['90/100', '88/100', '35/100']})
df['rating'] = df['rating'].apply(lambda x: x.split('/')[0]).astype(int)
print(df)

Returns:

   rating
0  90
1  88
2  35

The more generic computation if the grade is in the format X/Y:

df['rating'] = df['rating'].apply(lambda x: (int(x.split('/')[0]) / int(x.split('/')[1])) * 100).astype(int)

Or shortly, but extremely unsafe and not a good practice at all:

df['rating'] = df['rating'].apply(lambda x: eval(x) * 100).astype(int)

You can use it if you’re just "fiddling around" with Python 🙂

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