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.
- Count the NaN values in one or more columns in Pandas DataFrame
- How to widen output display to see more columns in Pandas dataframe?
- Sort the Pandas DataFrame by two or more columns
- Change the order of a Pandas DataFrame columns in Python
- How to drop one or multiple columns in Pandas Dataframe
- Select all columns, except one given column in a Pandas DataFrame
- How to Check the Data Type in Pandas DataFrame?
- Change the data type of a column or a Pandas Series
- Python | Delete rows/columns from DataFrame using Pandas.drop()
- How to select multiple columns in a pandas dataframe
- How to rename columns in Pandas DataFrame
- Difference of two columns in Pandas dataframe
- Split a text column into two columns in Pandas DataFrame
- Getting frequency counts of a columns in Pandas DataFrame
- Dealing with Rows and Columns in Pandas DataFrame
- Iterating over rows and columns in Pandas DataFrame
- Split a String into columns using regex in pandas DataFrame
- Create a new column in Pandas DataFrame based on the existing columns
- Using dictionary to remap values in Pandas DataFrame columns
- Conditional operation on Pandas DataFrame columns
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.