Sub topic 7
Converting existing columns
This chapter covers how to move text columns that already exist in a DataFrame from object to the string dtype. It assumes you know what a dtype is, can build and index a Series or DataFrame, and have met the string dtype and pd.NA in earlier chapters. The examples were written for pandas 2.x. Printed dtype names can differ in pandas 3, which a later chapter covers.
Why conversion needs care
A conversion changes more than the dtype label. It changes three things:
- How missing values are stored:
NoneandNaNboth becomepd.NA. - What non-string values become: numbers and other objects are turned into text.
- What downstream operations return: comparisons and
.strmethods on astringcolumn return nullable results, not plainboolorfloatvalues.
A good conversion makes these changes on purpose and checks them afterwards. Pandas gives you three tools: astype, convert_dtypes, and the dtype arguments of the readers.
| Tool | Scope | Best for |
|---|---|---|
| `Series.astype("string")` | One column, explicit | A column you know is text |
| `DataFrame.astype({...})` | Chosen columns, explicit | Predictable, reviewable conversions |
| `DataFrame.convert_dtypes()` | Every column, inferred | Quick cleanup of a whole frame |
| `read_csv(dtype=...)` or `dtype_backend=` | At load time | Avoiding `object` from the start |
Converting one column with astype
Use the string "string", not the Python type str. They look similar but behave differently.
import numpy as np
import pandas as pd
s = pd.Series(["apple", None, np.nan, 42])
print(s.dtype)
print(s.astype(str).tolist())
print(s.astype("string").tolist())In pandas 2.x, astype(str) returns an object column in which the missing values have become the literal text "None" and "nan". The output is ['apple', 'None', 'nan', '42']. Those are real strings, so isna() reports no missing data and filters will match them.
astype("string") gives ['apple', <NA>, <NA>, '42']. Both missing markers become pd.NA, and the integer 42 becomes the text "42".
Non-string values are converted, not rejected
astype("string") calls the equivalent of str() on each non-missing element. For an object column holding numbers, dates, or other objects, the result is their text form. Floats keep their decimal point, so 1.0 becomes "1.0". If a column mixes real text with accidental numbers, the numbers become text and the conversion does not warn you.
After conversion the column is strict about what you put into it. Assigning a non-string value into a string column raises an error:
import pandas as pd
t = pd.Series(["a", "b"], dtype="string")
try:
t[0] = 1
except TypeError as err:
print("TypeError:", err)
t[0] = "z"
t[1] = pd.NA
print(t.tolist())This strictness is useful. An object column accepts anything, so a stray number can appear later and break .str calls. A string column rejects it at the point of assignment.
Converting several columns with a dictionary
DataFrame.astype accepts a mapping from column name to dtype. Listing the columns makes the conversion easy to review, and it leaves numeric columns alone.
import numpy as np
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", None],
"code": ["A1", "B2", np.nan],
"visits": [3, 5, 2],
}
)
before_missing = df.isna().sum()
converted = df.astype({"city": "string", "code": "string"})
print(converted.dtypes)
print(converted.isna().sum().equals(before_missing))The last line is a cheap safety check. The number of missing values per column must not change. If it does, text such as "None" was created or a value was lost.
To convert every object column without naming each one, build the dictionary from the dtypes:
import pandas as pd
df = pd.DataFrame({"a": ["x", None], "b": ["y", "z"], "n": [1, 2]})
object_cols = df.select_dtypes(include="object").columns
converted = df.astype({col: "string" for col in object_cols})
print(converted.dtypes)Do this only when you have confirmed that every object column really holds text. Object columns can also hold lists, dictionaries, or Decimal values, and astype("string") would flatten those into text.
Letting pandas infer with convert_dtypes
convert_dtypes inspects each column and picks the best nullable dtype. For text, that is string.
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)Here city changes from object to string and visits changes from int64 to Int64. Numbers are converted too, because convert_dtypes handles the whole frame. The inference has rules you should know:
- An
objectcolumn of strings, or strings and missing values, becomesstring. - A float column whose non-missing values are all whole numbers becomes
Int64. A column[1.0, 2.0, NaN]becomesInt64with one<NA>. - A column of
TrueandFalsebecomesboolean. - An
objectcolumn that mixes types, such as[1, "a", None], staysobject.
Each rule has a switch: convert_string, convert_integer, convert_boolean, and convert_floating. To convert only text and leave numbers as they are, turn the others off:
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", None],
"visits": [3, 5, 2],
"score": [1.0, 2.0, 3.5],
}
)
text_only = df.convert_dtypes(
convert_integer=False,
convert_floating=False,
convert_boolean=False,
)
print(text_only.dtypes)The object column city becomes string. The integer column visits and the float column score are unchanged.
Choose between astype and convert_dtypes by how much surprise you can tolerate. convert_dtypes is convenient for exploration. In a pipeline that other people read, an explicit astype mapping documents which columns are text and fails loudly if a column is missing.
Avoiding object at load time
The cheapest conversion is the one you never need. Readers such as read_csv accept a dtype mapping, so the text column is created as string from the start. Empty fields become <NA> directly.
import io
import pandas as pd
csv = "name,visits\nAda,3\n,5\nAlan,\n"
df = pd.read_csv(io.StringIO(csv), dtype={"name": "string", "visits": "Int64"})
print(df.dtypes)
print(df)If you want nullable dtypes for every column, set dtype_backend:
import io
import pandas as pd
csv = "name,visits\nAda,3\n,5\nAlan,\n"
df = pd.read_csv(io.StringIO(csv), dtype_backend="numpy_nullable")
print(df.dtypes)With "numpy_nullable", text columns load as string and integer columns as Int64. This is the loading-time equivalent of convert_dtypes. The dtype_backend argument is available in pandas 2.0 and later.
Empty strings are not missing values
Conversion only maps None and NaN to pd.NA. An empty string "" is a real value, and it stays "". Data exported from spreadsheets often contains both kinds of blank. If you want them treated alike, convert the empty strings explicitly:
import pandas as pd
s = pd.Series(["a", "", None, "b"], dtype="string")
print(s.isna().tolist())
cleaned = s.replace("", pd.NA)
print(cleaned.isna().tolist())The first line prints [False, False, True, False]. After the replacement, the empty string also counts as missing, so the second line prints [False, True, True, False]. Decide on this deliberately. Whitespace-only cells such as " " need .str.strip() first.
Converting back and moving to other types
Going back to object is a plain astype(object). The missing values stay as pd.NA, not NaN, so code that tests with np.isnan will fail on them:
import pandas as pd
s = pd.Series(["a", None], dtype="string")
print(s.astype(object).tolist())To turn text into numbers, convert the string column to a nullable numeric dtype. Missing entries stay missing:
import pandas as pd
s = pd.Series(["1", "2", None], dtype="string")
print(s.astype("Int64").tolist())If some entries are not valid numbers, astype raises an error. Use pd.to_numeric(s, errors="coerce") to turn bad entries into missing values, then inspect which rows were affected.
A checklist for a safe conversion
- Look at
df.dtypesanddf.isna().sum()before you start. - Check that each
objectcolumn contains only text.s.map(type).value_counts()shows the Python types in a column. - Convert with an explicit
astypemapping, or withconvert_dtypesand a review of the result. - Compare the missing-value counts before and after.
- Decide how to treat empty strings and whitespace.
- Re-run the code that uses these columns. Comparisons now return
booleanwith<NA>, and.strmethods return nullable results.
Exercise
A column contains ["x", None, "y"] with dtype object. You run s.astype(str) in pandas 2.x and then s.isna().sum() on the result. What do you get, and what should you have used instead?
Show answer
The result is 0. astype(str) turns None into the text "None", so nothing is missing any more. Use s.astype("string"), which stores the missing entry as pd.NA, so isna().sum() is 1.
Exercise
You load a CSV with read_csv and a column "code" arrives as object. Name two ways to get it as a string column, one at load time and one after loading.
Show answer
At load time, pass dtype={"code": "string"} to readcsv, or pass dtypebackend="numpynullable" to convert all columns. After loading, use df.astype({"code": "string"}), or df.convertdtypes() if you want inference across the whole frame.
Exercise
After converting a column to string, s.isna().sum() is unchanged, but the column still shows blank-looking entries. What is the likely cause and the fix?
Show answer
The blanks are empty strings, or whitespace-only strings, which are real values and not missing. Fix them with s.str.strip() followed by s.replace("", pd.NA), if you want them treated as missing.