Data Types and astype()
Every column in a DataFrame has a single dtype (data type). The dtype decides which operations make sense, how much memory the column uses and how values are printed. Getting the types right is often the first step of an analysis: a number stored as text can't be summed, and a date stored as text can't be compared.
The main dtypes
| dtype | Holds | Example values |
|---|---|---|
int64 |
whole numbers | 3, -12 |
float64 |
decimal numbers (and NaN) | 2.5, NaN |
bool |
True/False | True |
object |
Python objects, usually strings | "Lisbon" |
datetime64[ns] |
dates and times | 2024-05-01 09:30 |
timedelta64[ns] |
durations | 3 days 04:00:00 |
category |
a fixed set of labels | "S", "M", "L" |
string, Int64, Float64, boolean |
"nullable" versions that support <NA> |
import pandas as pd
order = pd.DataFrame({
"qty": [3, 1, 4],
"price": [9.99, 24.5, 3.0],
"gift": [False, True, False],
"city": ["Riga", "Oslo", "Bern"],
"placed": pd.to_datetime(["2024-02-01", "2024-02-03", "2024-02-03"]),
})
print(order.dtypes)qty int64
price float64
gift bool
city object
placed datetime64[ns]
dtype: object
Converting with astype()
astype() converts a column (or a whole frame) to another type:
import pandas as pd
raw = pd.DataFrame({
"room": ["101", "102", "205"],
"guests": ["2", "4", "1"],
"rate": ["89.0", "120.5", "64.0"],
})
print(raw.dtypes)
print(raw["guests"].sum()) # text "sum" just concatenates
typed = raw.astype({"guests": "int64", "rate": "float64"})
print(typed.dtypes)
print(typed["guests"].sum(), typed["rate"].mean())room object
guests object
rate object
dtype: object
241
room object
guests int64
rate float64
dtype: object
7 91.16666666666667
Notice that room stayed text on purpose: room numbers are labels, not quantities. You'd never add two room numbers together.
Note:
astype(int)fails if any value can't be converted (like"n/a") or if the column contains NaN. Usepd.to_numeric(s, errors="coerce")first for messy data.
The NaN problem with integers
A classic int64 column cannot hold missing values, so a single NaN turns the whole column into float64. The nullable dtypes (written with a capital letter) fix this:
import pandas as pd
visits = pd.Series([12, None, 7, 30])
print(visits)
print(visits.astype("Int64"))
print(visits.astype("Int64").sum())0 12.0
1 NaN
2 7.0
3 30.0
dtype: float64
0 12
1 <NA>
2 7
3 30
dtype: Int64
49
The nullable Int64 keeps whole numbers and shows the missing value as <NA>.
convert_dtypes() and the string dtype
convert_dtypes() picks the best nullable type for every column automatically. Text becomes the dedicated string dtype instead of the generic object:
import pandas as pd
df = pd.DataFrame({
"score": [7.0, None, 9.0],
"name": ["Ali", "Bea", None],
"passed": [True, None, True],
})
print(df.dtypes)
print(df.convert_dtypes().dtypes)
print(df.convert_dtypes())score float64
name object
passed object
dtype: object
score Int64
name string[python]
passed boolean
dtype: object
score name passed
0 7 Ali True
1 <NA> Bea <NA>
2 9 <NA> True
Memory and downcasting
Smaller types use less memory, which matters for millions of rows. memory_usage(deep=True) reports bytes per column:
import pandas as pd
n = 10_000
df = pd.DataFrame({
"store_id": [i % 50 for i in range(n)],
"size": ["small", "medium", "large", "medium"] * (n // 4),
})
before = df.memory_usage(deep=True)
slim = df.astype({"store_id": "int8", "size": "category"})
after = slim.memory_usage(deep=True)
print(pd.DataFrame({"before": before, "after": after})) before after
Index 72 72
store_id 80000 10000
size 305000 10155
Store ids from 0 to 49 fit in int8 (range −128…127), using one byte each instead of eight. Repeated text labels shrink dramatically as category (see the Categorical Data lesson).
Selecting columns by type
select_dtypes() picks columns by kind, which is handy for applying the same step to every numeric or every text column:
import pandas as pd
df = pd.DataFrame({
"sku": ["A1", "B2"],
"price": [4.5, 12.0],
"qty": [10, 3],
"active": [True, False],
})
print(df.select_dtypes(include="number").columns.to_list())
print(df.select_dtypes(include="object").columns.to_list())
print(df.select_dtypes(exclude=["number", "bool"]).columns.to_list())['price', 'qty']
['sku']
['sku']
Test yourself
A column of integers gets one missing value. What dtype does it become by default?
- int64
- float64
- object
- Int64
Which call converts the qty column to whole numbers?
- df["qty"].astype("int64")
- df["qty"].to("int")
- df["qty"].dtype = int
- int(df["qty"])
What does df.select_dtypes(include="number") return?
- The number of columns
- Only the numeric columns
- The dtypes of each column
- Rows that contain numbers