18 Apr Change Datatype in Pandas
The astype() method in pandas converts a DataFrame or Series to a specific data type. It is essential for data cleaning, such as turning string-based numbers into actual integers or floats for calculations.
Let us see an example to convert data types in a Pandas Dataframe:
import pandas as pd
# 1. Create a sample DataFrame with strings
data = {
'age': ['25', '30', '35'],
'height': ['165.5', '180.2', '175.0'],
'is_member': [1, 0, 1]
}
df = pd.DataFrame(data)
# 2. Convert specific columns using a dictionary
df = df.astype({
'age': int,
'height': float,
'is_member': bool
})
print(df.dtypes)
Output
age int64 height float64 is_member bool dtype: object
If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments