🎓 A1Learner
🔍
0 of 50 lessons completed

Changing Types

astype changes a column type. to_numeric turns text that looks like numbers into real numbers.

Text numbers are not numbers

The units are text, so the sum joins them into "213".

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": ["2", "1", "3"],
})
print(df["units"].sum())

astype turns them into numbers

astype(int) changes the text into real numbers. The sum is now 6.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": ["2", "1", "3"],
})
df["units"] = df["units"].astype(int)
print(df.dtypes)
print(df["units"].sum())

to_numeric handles bad text

The word "many" is not a number, so errors="coerce" turns it into NaN.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": ["2", "many", "3"],
})
print(pd.to_numeric(df["units"], errors="coerce"))

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
sales["price"] = sales["price"].astype(int)
print(sales[["product", "price"]].head())
print(sales["price"].sum())

Key points

  • Use astype to change a column to a new type, like int.
  • A sum of text numbers joins them, so "2", "1", and "3" give "213".
  • Use to_numeric to turn a text column into numbers.
  • Use errors="coerce" to turn text that is not a number into NaN.
  • Check the change with dtypes, which lists the type of each column.

In this example, the sales table is read from the CSV text. astype(int) changes the price column from decimal numbers to whole numbers. head shows the first five prices as whole numbers, and the sum of all twelve is 112.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which code turns a text column of numbers into real numbers?