How to convert an object that is a fraction to an integer in Python?

Question:

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, etc.

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

I tried .astype and int(float()).

Asked By: Robbie Anderson

||

Answers:

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 🙂

Answered By: no_hex

You will have to round it up to the nearest interger value and then you can cast it to a interger so for example 3/5 would be 0.6 but if you try cast that, it won’t work since its a decimal value but if you round it up you can cast it to a interger

Also depends on what you’d like to do

Answered By: Swinging Treebranch
s = '60/100'
int(s.split('/')[0])
Answered By: Leonid Astrin

Try this code:

result = int(valueOfyoucolumn) * 100

By this, you are removing the fraction and you convert the results into an interger.

Answered By: Nicolas Pellerin

'98/100' is a string representing a fraction.

@no_hex’s answer shows a way to parse the numerator using string operations.
However Python has also support for fractions, so it might be easier to use those.

>> from fractions import Fraction
>> s = "98/100"
>> int(Fraction(s) * 100)
98

As a side benefit, this will also give the correct answer if the fraction denominator is different.

>> s = "3/4"
>> float(Fraction(s) * 100)
75.0
Answered By: Jakube
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.