Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

 I need to convert my entire dataframe instead of just a series. The to_numeric function only works on one series at a time and is not a good replacement for the deprecated convert_objects command. Is there a way to get similar results to the convert_objects(convert_numeric=True) command in the new pandas' release?

What if in my dataframe I had strings that could not be converted into integers? Example:

df = pd.DataFrame({'ints': ['3', '5'], 'Words': ['Kobe', 'Bryant']})

df.dtypes

Out[59]: 

Words    object

ints     object

dtype: object

Then I could run the deprecated function and get:

df = df.convert_objects(convert_numeric=True)

df.dtypes

Out[60]: 

Words    object

ints      int64

dtype: object

Running the apply command gives me errors, even with try and except handling.

1 Answer

0 votes
by (107k points)

You can simply apply the following function to all columns:

df.apply(pd.to_numeric)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...