Last Updated : 23 Jul, 2025
In data analysis, ensuring that each column in a Pandas DataFrame has the correct data type is crucial for accurate computations and analyses. The most common way to change the data type of a column in a Pandas DataFrame is by using the astype() method. This method allows you to convert a specific column to a desired data type. Here's the example:
Using astype() method Python
import pandas as pd
data = {'Name': ['John', 'Alice', 'Bob', 'Eve', 'Charlie'],
'Age': [25, 30, 22, 35, 28],
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male'],
'Salary': [50000, 55000, 40000, 70000, 48000]}
df = pd.DataFrame(data)
# Convert 'Age' column to float type
df['Age'] = df['Age'].astype(float)
print(df.dtypes)
Name object Age float64 Gender object Salary int64 dtype: objectConverting a Column to a DateTime Type
Sometimes, a column that contains date information may be stored as a string. You can convert it to the datetime type using the pd.to_datetime() function.
Python
# Example: Create a 'Join Date' column as a string
df['Join Date'] = ['2021-01-01', '2020-05-22', '2022-03-15', '2021-07-30', '2020-11-11']
# Convert 'Join Date' to datetime type
df['Join Date'] = pd.to_datetime(df['Join Date'])
print(df.dtypes)
Name object Age int64 Gender object Salary int64 Join Date datetime64[ns] dtype: objectChanging Multiple Columns' Data Types
If you need to change the data types of multiple columns at once, you can pass a dictionary to the astype() method, where keys are column names and values are the desired data types.
Python
# Convert 'Age' to float and 'Salary' to string
df = df.astype({'Age': 'float64', 'Salary': 'str'})
print(df.dtypes)
Name object Age float64 Gender object Salary object dtype: object
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4