Change Data Type for one or more columns in Pandas Dataframe
Let’s see the different ways of changing Data Type for one or more columns in Pandas Dataframe.
Method #1: Using DataFrame.astype()
We can pass any Python, Numpy or Pandas datatype to change all columns of a dataframe to that type, or we can pass a dictionary having column names as keys and datatype as values to change type of selected columns.
Method #2: Using DataFrame.apply()
We can pass pandas.to_numeric, pandas.to_datetime and pandas.to_timedelta as argument to
apply() function to change the datatype of one or more columns to numeric, datetime and timedelta respectively.
Method #3: Using DataFrame.infer_objects()
This method attempts soft-conversion by inferring data type of ‘object’-type columns. Non-object and unconvertible columns are left unchanged.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course