Sub topic 7
Converting existing columns
This chapter assumes you know what a dtype is, how to create a Series or DataFrame, and the earlier chapters' material on object columns and pd.NA. Here you will move real data, which usually arrives as object, onto the string dtype.
Three ways to convert
Each method fits a different situation.
| Method | Scope | Use it when |
|---|---|---|
| `dtype="string"` at construction | One Series or DataFrame | You are building the data yourself |
| `astype("string")` | One column, or several via a dict | You know which columns are text |
| `convert_dtypes()` | Whole DataFrame or Series | You want pandas to infer the best nullable dtype for every column |
Converting one column with astype
astype("string") turns an object column into a string column. Missing entries become pd.NA.
import pandas as pd
s = pd.Series(["apple", "banana", None])
print(s.dtype)
t = s.astype("string")
print(t.dtype)
print(t.isna().tolist())The first line prints object, the second string, and the last [False, False, True]. To convert several columns, pass a dict: df.astype({"city": "string", "country": "string"}).
Why not astype(str)?
astype(str) looks similar but behaves differently in pandas 2. It calls Python's str() on every entry, including the missing ones. None becomes the text "None", and NaN becomes the text "nan". The column then has no missing values left. Later isna() and dropna() calls find nothing, and the fake strings can end up in your output.
import numpy as np
import pandas as pd
s = pd.Series(["a", None, np.nan])
print(s.astype(str).tolist())
print(s.astype("string").tolist())The first line shows 'None' and 'nan' as strings. The second shows <NA> in both positions.
Converting everything with convert_dtypes
DataFrame.convert_dtypes() inspects each column and picks a nullable dtype. Object columns of strings become string, integers become Int64, floats become Float64, and booleans become boolean.
import pandas as pd
df = pd.DataFrame({"city": ["Oslo", "Lima", None], "visits": [3, 5, 2]})
print(df.dtypes)
converted = df.convert_dtypes()
print(converted.dtypes)Before conversion, city is object and visits is int64. Afterwards, city is string and visits is Int64. The capital I marks the nullable integer type, which can hold pd.NA.
Two behaviours are worth knowing:
- A column is converted to
stringonly if all its non-missing values are strings. A column that mixes strings and numbers staysobject. Clean it first, or convert it explicitly withastype("string"). - You can switch off parts of the inference. For example,
df.convert_dtypes(convert_integer=False)leaves integer columns alone, andconvert_string=Falseleaves text columns asobject.
Choosing a path
Common errors
- Converting too early. If a column holds numbers stored as text, such as
"001"and"042", converting it tostringkeeps the leading zeros. Converting it to a number does not. Decide which meaning you want before you convert. - Expecting
int64to stay.convert_dtypes()changes numeric columns as well. Code that relied onint64orfloat64behaviour, such as NumPy interop, may need a second look. - Forgetting to assign. Neither
astypenorconvert_dtypesworks in place. Assign the result back, as indf["city"] = df["city"].astype("string"). - Mixed columns left as object. If
convert_dtypes()leaves a column asobject, check it withdf["col"].map(type).value_counts()to see which types are mixed in.
Exercise
A column called code holds ["A1", None, "B2"] with dtype object. You run df["code"] = df["code"].astype(str). What does the column contain, and what should you have written instead?
Show answer
In pandas 2, it contains "A1", "None", and "B2", so the missing value has become the text "None" and isna() no longer finds it. Write df["code"] = df["code"].astype("string"), which keeps the missing entry as pd.NA.