Reputation: 3
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())
.
Upvotes: 0
Views: 390
Reputation: 13
Try this code:
result = int(valueOfyoucolumn) * 100
By this, you are removing the fraction and you convert the results into an interger.
Upvotes: -2
Reputation: 1842
Taking into account that:
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 :-)
Upvotes: 2
Reputation: 3565
'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
Upvotes: 2
Reputation: 21
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
Upvotes: -1