Home > OS >  i cannot convert the data type of one column from object to int or float in dataframe
i cannot convert the data type of one column from object to int or float in dataframe

Time:05-08

I have been learning data analysis and visualization using Python but I am having trouble on changing datatypes of certain dataframe components from one form to another In this code snippet I want to change the fractional data to integer I need to change the RottenTomatoes and IMDb to integer or float so that I can use visualization models and convert the fractional data to integer screenshot of the dataframe output

I tried to convert them using the following code:

movieRatings['RottenTomatoes'] = movieRatings['RottenTomatoes'].fillna(0/100).astype('int')

The following error was called:

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

CodePudding user response:

I am assuming that you want to extract the numerator of those fractions and convert it into an int (or a float).

If this is the case, to convert into int you can:

>>> int(('95/100').split('/')[0])
95

In pandas, this will become:

movieRatings['RottenTomatoes'] = movieRatings['RottenTomatoes'].fillna('0/100').apply(lambda x: int((x).split('/')[0]))

Bear in mind that you should also change your .fillna, so that the value is a string (0/100 is a float).

CodePudding user response:

You can try

movieRatings['RottenTomatoes'] = movieRatings['RottenTomatoes'].fillna('0/100').apply(eval)

# or

import ast

movieRatings['RottenTomatoes'] = movieRatings['RottenTomatoes'].fillna('0/100').apply(ast.literal_eval)
   RottenTomatoes
0            0.99
1            0.96
2            0.00
  • Related