Skip to main content

How to Change a Column's Type in pandas with astype

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A column's type decides what pandas can do with it and what a library on the other end accepts: whole numbers, decimals, text. astype converts a column to another type. This guide turns a column of whole numbers into decimals, with real output from pandas 3.1.1.

Syntax​

Syntax
<dataframe>["<column>"] = <dataframe>["<column>"].astype("<type>")
PartWhat it means
"<type>"The new type, such as "float64", "int64" or "str"
The assignmentastype returns a converted copy; assigning it puts it back in the DataFrame

The pandas reference: "Cast a pandas object to a specified dtype dtype."

Prerequisites​

  • pandas in your project, for example with uv add pandas. This guide uses pandas 3.1.1 on Python 3.15.2.

Step 1: Write the Script​

change_type.py
import pandas as pd

orders = pd.DataFrame({"quantity": [1, 2, 3]})
print(orders.dtypes)

orders["quantity"] = orders["quantity"].astype("float64")
print(orders.dtypes)
print(orders)

The change_type.py script in a macOS-style code window: an orders DataFrame with a quantity column of 1, 2 and 3, print of its dtypes, then quantity converted with astype("float64"), and the dtypes and DataFrame printed again.

Step 2: Run It​

Terminal
uv run python change_type.py
Output
quantity int64
dtype: object
quantity float64
dtype: object
quantity
0 1.0
1 2.0
2 3.0

The script's output in a terminal: quantity int64, then quantity float64, then the values 1.0, 2.0 and 3.0.

The column was int64 and is now float64, and the values print with a decimal point.

Common Mistakes​

MistakeWhat happensDo this instead
Calling astype without assigning the resultThe DataFrame keeps its old type: it still said quantity int64Assign it back: orders["quantity"] = orders["quantity"].astype("float64")
Converting text that isn't a numberValueError: invalid literal for int() with base 10: 'two'Clean the values first, or use pd.to_numeric(..., errors="coerce"), below

Troubleshooting​

SymptomLikely causeFix
ValueError: invalid literal for int()A value in the column can't become that typeFind it: print the column, or the rows where pd.to_numeric(..., errors="coerce") gives a missing value

FAQ​

What does pd.to_numeric with errors="coerce" do?​

It converts what it can and turns the rest into missing values instead of raising an error: for "1", "two" and "3" it gave 1.0, NaN and 3.0, so the bad value is easy to find.

Can I change several columns at once?​

Yes, with a dictionary: astype({"quantity": "float64", "price": "float64"}) turned both columns into float64.

Conclusion​

orders["quantity"].astype("float64"), assigned back to the column, turned int64 into float64. Text that isn't a number raises ValueError until it's cleaned.

Additional Resources​