Pandas Change Datatype
Last Updated :
13 Jan, 2025
Improve
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
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)
Output
Name object Age float64 Gender object Salary int64 dtype: object
Converting 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.
# 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)
Output
Name object Age int64 Gender object Salary int64 Join Date datetime64[ns] dtype: object
Changing 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.
# Convert 'Age' to float and 'Salary' to string
df = df.astype({'Age': 'float64', 'Salary': 'str'})
print(df.dtypes)
Output
Name object Age float64 Gender object Salary object dtype: object