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

Advertisements

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

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 🙂

Leave a ReplyCancel reply