typestar

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

  1. astype converts a column; the nullable types start capitalised.
  2. to_numeric with coerce turns junk into missing values.
  3. memory_usage shows what a category saves.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Series & frames, step 4 of 26 in pandas.

← Previous Next →