Sub topic 3
Converting a Column with astype
This chapter assumes you can build a DataFrame, select columns with df["col"], and read a CSV with pandas. You should also have seen df.dtypes and know why text columns show up as object. Here you learn the general-purpose conversion tool, astype, and where it stops being the right choice.
What astype does
astype converts the values of a Series to a new dtype. It returns a new Series and leaves the original unchanged. If you want the change to stick, assign the result back.
import pandas as pd
df = pd.DataFrame({
"qty": ["3", "5", "7"],
"score": [1, 2, 3],
"label": ["a", "b", "a"],
})
df["qty"] = df["qty"].astype("int64")
df = df.astype({"score": "float64", "label": "category"})
print(df.dtypes)The code prints int64 for qty, float64 for score, and category for label. The first line converts one column. The second passes a dictionary to DataFrame.astype, which converts several columns at once and leaves any column not named in the dictionary alone.
Calling df.astype("float64") with a single dtype tries to convert every column. That fails as soon as one column holds text that is not a number, so use the dictionary form unless every column really should change.
astype is strict. By default it raises an exception on the first value it cannot convert. It has no "coerce" mode that turns bad values into missing values. That behavior belongs to pd.to_numeric and pd.to_datetime, covered in later chapters.
Naming the target dtype
You can pass a dtype as a string, a NumPy type, or a Python type. Strings are the most common and the least ambiguous.
| Target string | Result | Allows missing values |
|---|---|---|
| `"int64"` | NumPy integer | No |
| `"float64"` | NumPy float | Yes, as `NaN` |
| `"Int64"` | Nullable integer (capital I) | Yes, as `<NA>` |
| `"boolean"` | Nullable boolean | Yes, as `<NA>` |
| `"string"` | Nullable text dtype | Yes, as `<NA>` |
| `"category"` | Categorical | Yes |
| `"datetime64[ns]"` | Timestamps | Yes, as `NaT` |
The capital letter matters. "int64" is the NumPy integer, which cannot hold a missing value. "Int64" is the pandas nullable integer, which can. The two look almost identical in code and behave differently.
What astype can parse
For text columns, astype relies on Python's own conversion rules. A string such as "3" converts to an integer, and "3.5" converts to a float. A string such as "3.5" does not convert to an integer.
import pandas as pd
s = pd.Series(["1", "2", "3.5"])
for target in ["float64", "int64"]:
try:
print(target, s.astype(target).tolist())
except ValueError as err:
print(target, "failed:", err)The float conversion succeeds and prints [1.0, 2.0, 3.5]. The integer conversion fails with invalid literal for int() with base 10: '3.5'. The error message names the first offending value, which helps when you debug.
Text with decoration fails in the same way. "$1,200", "12%", and " n/a " all raise ValueError when converted to a number. Clean the strings first, or use pd.to_numeric with errors="coerce".
Integer columns and missing values
A NumPy integer column cannot store a missing value. If a Series of numbers contains None, pandas stores it as float64 and uses NaN. Converting that column to int64 raises an error.
import pandas as pd
s = pd.Series([1, 2, None])
print(s.dtype)
try:
s.astype("int64")
except ValueError as err:
print("int64 failed:", err)
print(s.astype("Int64"))The first print shows float64. The conversion to int64 fails with a message about non-finite values. The conversion to Int64 succeeds, and the missing entry becomes <NA>. The values 1 and 2 are whole numbers, so nothing is lost. Nullable dtypes get their own chapter later in this series.
Floats to integers: truncation and checks
Converting a float to int64 drops the fractional part. It does not round.
import pandas as pd
s = pd.Series([1.9, 2.5, -1.9])
print(s.astype("int64").tolist())
print(s.round().astype("int64").tolist())The first line prints [1, 2, -1], because truncation moves values toward zero. The second line rounds first and prints [2, 2, -2]. Python's round and Series.round round halves to the nearest even number, so 2.5 becomes 2.
Silent truncation is a common source of subtle bugs. Before you convert a float column that should hold whole numbers, check that it does:
import pandas as pd
s = pd.Series([1.0, 2.0, 3.0, 4.5])
fractional = s[s % 1 != 0]
print(fractional)This prints the row with 4.5. If the result is empty, the conversion loses nothing. If it is not empty, decide whether those rows are errors or whether rounding is acceptable.
Gotchas with bool and str
Two target dtypes behave in ways that surprise people.
astype(bool) does not read words
astype(bool) applies Python truthiness. Any non-empty string is True, including "no" and "False".
import pandas as pd
answers = pd.Series(["yes", "no", ""])
print(answers.astype(bool).tolist())The output is [True, True, False]. Only the empty string is falsy. To convert answer words correctly, map them explicitly. A later chapter shows how.
astype(str) can turn missing values into text
In pandas 2.x and earlier, astype(str) converts missing values into the literal strings "None" or "nan". Those strings then look like real data.
import pandas as pd
s = pd.Series(["a", None])
print(s.astype(str).tolist())
print(s.astype("string").tolist())The first line prints ['a', 'None']. The second prints ['a', <NA>], because the "string" dtype keeps the missing value as missing. Pandas 3 changes the default text dtype, so check pd.__version__ and test on your own installation if you depend on this behavior.
Choosing between astype and the parsers
astype works well when the data is already clean and you only need to change the storage type. For messy text, the specialized functions give you more control.
A practical rule: use astype when a failure should stop your program. A strict conversion that raises an error is often what you want in a pipeline, because it exposes bad data instead of hiding it. Use to_numeric or to_datetime with errors="coerce" when bad values are expected and you plan to inspect them afterward.
Verifying the conversion
After any conversion, confirm two things: the dtype changed, and no values were lost or altered.
import pandas as pd
raw = pd.DataFrame({"qty": ["3", "5", "7"], "price": ["1.5", "2.0", "4.25"]})
clean = raw.astype({"qty": "int64", "price": "float64"})
print(clean.dtypes)
print(clean.isna().sum())
print(clean["qty"].sum(), clean["price"].sum())The dtypes confirm the new types. The isna().sum() call shows that no missing values appeared. The sums confirm that arithmetic now works, which would have failed or concatenated text while the columns were strings.
Common errors
ValueError: invalid literal for int(): a string contains something other than digits, such as a decimal point, a symbol, or a space-only value. Clean it, or convert to float first.ValueErrorabout non-finite values: the column holdsNaNand you asked forint64. Use"Int64"instead.- Dtype unchanged after the call: you did not assign the result. Write
df["col"] = df["col"].astype(...). - Everything became
True: you usedastype(bool)on text. - Strings
"nan"or"None"in the data: you usedastype(str)on a column with missing values.
Exercise
A column qty holds the strings "4", "9", and None. You run df["qty"].astype("int64") and get a ValueError. Write the conversion that works and keeps the missing value, and say what the result's dtype and missing entry look like.
Show answer
Use df["qty"].astype("float64").astype("Int64"), or pd.to_numeric(df["qty"]).astype("Int64"). The result has dtype Int64, with values 4, 9, and <NA>. The int64 conversion fails because NumPy integers cannot hold a missing value, while the nullable Int64 can.
Exercise
The Series s = pd.Series([2.0, 3.0, 7.8]) should hold whole numbers. What does s.astype("int64") return, and how can you detect the problem before converting?
Show answer
It returns [2, 3, 7], because the conversion truncates 7.8 to 7 without any warning. Detect it first with s[s % 1 != 0], which returns the row containing 7.8. If that result is not empty, the column has fractional values and converting it will lose information.