How to Change Column Type in Pandas?
In Pandas, you can change the column data type using the astype()
method.
For example, let's say you have a DataFrame df with a column 'age' that is currently of type object (string) and you want to convert it to type int:
import pandas as pd
# create an example DataFrame
data = {'name': ['Alice', 'Bob', 'Charlie'],
'age': ['25', '30', '35']}
df = pd.DataFrame(data)
# check the data types of each column
print(df.dtypes)
# Output:
# name object
# age object
# dtype: object
# convert the 'age' column to type int
df['age'] = df['age'].astype(int)
# check the data types of each column again
print(df.dtypes)
# Output:
# name object
# age int32
# dtype: object
In this example, we first create a DataFrame df
with a column 'age' of type object (i.e., string). We use the dtypes
method to check the data types of each column. Then, we convert the 'age' column to type int using .astype(int)
. Finally, we use .dtypes
again to check that the column type has been changed to int.
Note that if there are any non-numeric values in the 'age' column, the astype()
method will raise an error. In this case, you can first clean/transform the data to ensure it only contains numeric values before converting the column type.