How to Convert Multiple Types in a Pandas DataFrame

Published Dec 12, 2021  ∙  Updated May 2, 2022

How can we convert the types of multiple columns at once in a DataFrame?

We can use astype() to achieve this.

Cast a single column with astype()

Suppose we have a column col that is of type float. We want to convert that to an int type.

We can do this like so.

df['col'] = df['col'].astype(int)

We can confirm that the casting was successful by checking the DataFrame dtypes.

print(df.dtypes)

Cast multiple columns with astype()

If we want to cast multiple columns, we can pass in a dictionary of column names along with the desired dtype.

df = df.astype({'col1': float, 'col2': str})

Once again, let’s confirm that everything converted as expected.

print(df.dtypes)

Read the Pandas documentation to learn about what other dtypes are available for casting.