Sub topic 6
Converting column types
This chapter covers changing a column's dtype (its data type) with astype, to_numeric, and to_datetime. It assumes you can build a DataFrame, select a column by name, and read basic Python. You also need to know that assigning to df["name"] creates or replaces a column, as the earlier chapters showed.
Why dtypes matter
Data read from CSV files, spreadsheets, or web forms often arrives as text. A column of prices stored as strings looks fine when printed, but "10" + "5" gives "105", sorting is alphabetical, and .dt or arithmetic operations fail. Converting a column creates a new Series with the right dtype. You then assign it back to the same column or to a new one.
Check dtypes first:
import pandas as pd
df = pd.DataFrame({
"id": ["1", "2", "3"],
"price": ["1.5", "12.0", "30"],
"signup": ["2026-01-15", "2026-02-03", "2026-03-20"],
})
print(df.dtypes)
df.info()All three columns are text. Which function you use to convert them depends on how much you trust the data.
astype: the strict general tool
astype converts a whole Series, or several columns at once when you pass a dictionary. It raises an error if any value cannot be converted.
df = df.astype({"id": "int64", "price": "float64"})
print(df.dtypes)Use astype when you know the data is clean. A failure then signals a real problem, and you want to see it.
Truncation and NaN
Converting floats to integers drops the fractional part. It does not round.
s = pd.Series([1.9, -1.9, 2.5])
print(s.astype(int))The result is 1, -1, 2. Call .round() first if you want rounding.
Standard NumPy integer dtypes cannot hold missing values. This raises a ValueError:
pd.Series([1.0, None, 3.0]).astype("int64")The fix is a nullable integer dtype. Its name starts with a capital letter:
ints = pd.Series([1.0, None, 3.0]).astype("Int64")
print(ints)The missing value is shown as <NA>, and the other values stay integers.
Nullable dtypes
pandas has nullable counterparts for common types. They use pd.NA for missing data instead of forcing a fallback to float or object.
| Plain dtype | Nullable dtype | Missing marker |
|---|---|---|
| `int64` | `Int64` | `<NA>` |
| `float64` | `Float64` | `<NA>` |
| `bool` | `boolean` | `<NA>` |
| `object` (text) | `string` | `<NA>` |
df.convert_dtypes() picks nullable dtypes for every column automatically. It is convenient for exploration. For production code, explicit astype calls document your intent better.
to_numeric: tolerant parsing
Real data has stray symbols and placeholders. pd.to_numeric takes an errors argument that controls what happens to values it cannot parse:
"raise"(the default) stops with an error."coerce"replaces bad values withNaN.
raw = pd.Series(["$1,200", "850", "n/a", None])
cleaned = raw.str.replace(r"[$,]", "", regex=True)
amount = pd.to_numeric(cleaned, errors="coerce")
print(amount)The .str.replace step removes the dollar sign and comma first, because to_numeric does not understand currency formatting. The result is 1200.0, 850.0, NaN, NaN.
Coercion hides problems, so check what it discarded. A value is a conversion failure if the original was present but the result is missing:
failed = raw[amount.isna() & raw.notna()]
print(failed)Here failed contains "n/a". Look at this list before you continue, and decide whether those rows need fixing, dropping, or filling.
Downcasting
To save memory, to_numeric can shrink the result to the smallest type that fits:
small = pd.to_numeric(pd.Series(["1", "2", "300"]), downcast="integer")
print(small.dtype)This prints int16, because 300 does not fit in int8. Downcasting helps with large tables, but later arithmetic can overflow in small types, so use it only when memory is a real constraint.
to_datetime: parsing dates
pd.to_datetime converts strings, numbers, or mixed input to datetime64[ns]. It has the same errors options as to_numeric. Invalid dates become NaT, the datetime version of NaN.
df["signup"] = pd.to_datetime(df["signup"])
print(df["signup"].dtype)Always give a format for ambiguous text
Is 03/04/2026 the third of April or the fourth of March? Without help, pandas guesses, and the guess can silently be wrong across a mixed file. State the format:
dates = pd.Series(["03/04/2026", "25/12/2026", "31/02/2026"])
parsed = pd.to_datetime(dates, format="%d/%m/%Y", errors="coerce")
print(parsed)The first value is 3 April 2026. The last value is not a real date, so it becomes NaT. An explicit format also makes parsing much faster on large columns. Once the column is a datetime, the .dt accessor covered in the next chapter extracts parts such as the month.
Converting to text, categories, and booleans
To text
astype(str) turns every value into a Python string. In pandas 2.x, missing values become the literal text "nan", which then looks like real data. The "string" dtype keeps them missing:
vals = pd.Series([10, None, 30])
print(vals.astype(str).tolist())
print(vals.astype("string").tolist())The first list contains 'nan', and the second contains <NA>.
To category
A column with few distinct values and many rows is a good candidate for the category dtype. It stores each unique value once plus small integer codes.
regions = pd.Series(["North", "South", "North", "East"] * 25_000)
print(regions.memory_usage(deep=True))
print(regions.astype("category").memory_usage(deep=True))The category version uses a small fraction of the memory. It also supports ordered categories, which you will meet again in the binning chapter.
To boolean from text
Map the strings yourself, then use the nullable boolean dtype so unknown values stay missing:
answers = pd.Series(["yes", "no", "yes", "maybe"])
flag = answers.map({"yes": True, "no": False}).astype("boolean")
print(flag)"maybe" is not in the dictionary, so map returns NaN for it, and astype("boolean") turns that into <NA>.
Common errors
ValueError: invalid literal for int().astypemet text it cannot parse, such as"1,200"or"". Clean the strings or useto_numeric(errors="coerce").IntCastingNaNError. You tried to cast a column containingNaNto a NumPy integer dtype. UseInt64.- Dates that are off by month and day. You parsed
dd/mm/yyyytext without aformatordayfirst=True. - Column still shows
object. You calledastypebut did not assign the result. These methods return a new Series, so writedf["price"] = df["price"].astype(float). - A numeric column that silently became text. One stray string in a CSV column makes pandas read the whole column as text. Convert it with
to_numericand inspect the failures.
Exercise
A column qty holds the strings "4", "7", "?", and "10". Write code that converts it to a nullable integer column, and say what value the "?" row gets.
Show answer
Use df["qty"] = pd.to_numeric(df["qty"], errors="coerce").astype("Int64"). The "?" row becomes <NA>. The to_numeric call turns it into NaN and yields floats, and astype("Int64") then converts the other values to integers while keeping the missing one. Calling astype("Int64") directly on the strings would raise an error.
Exercise
The strings "05/06/2026" are day/month/year. Why is pd.to_datetime(s) risky, and what is the safer call?
Show answer
Without a format, pandas may read the text as month/day/year, which gives 6 May instead of 5 June, and it can do so without any warning. Use pd.to_datetime(s, format="%d/%m/%Y", errors="coerce"). This reads the dates the way you intend, turns invalid dates into NaT, and parses faster.