Types and conversion in Python
Pandas types decide what operations exist and how much memory it costs.
import pandas as pd
frame = pd.DataFrame({"n": ["1", "2", "oops"], "kind": ["a", "b", "a"]})
frame["n"] = pd.to_numeric(frame["n"], errors="coerce").astype("Int64")
frame["kind"] = frame["kind"].astype("category")
print(frame.dtypes)
print(frame)
print(frame.memory_usage(deep=True))
How it works
astypeconverts a column; the nullable types start capitalised.to_numericwith coerce turns junk into missing values.memory_usageshows what a category saves.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 10
- Characters to type
- 286
- Tokens
- 120
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 72 seconds.
Step 4 of 4 in Series & frames, step 4 of 26 in pandas.