astype() (Pandas)

s.astype() converts a Series or DataFrame column to a different dtype — for example text to numbers, floats to ints, or a string column to the memory-saving 'category' type. It is pandas' explicit type-cast.

Pandas

Use astype when pandas inferred the wrong type or when you need a specific one: astype(int), astype('float64'), astype('string'), or astype('category'). It returns a new object, so you reassign the column or the frame.

Casting can fail or lose information: converting a column that contains the text 'N/A' to int raises, and converting floats with decimals to int silently truncates. Clean or fill the data first, and consider the nullable integer dtype 'Int64' (capital I) when you need integers that can also hold missing values.

Downcasting is a cheap memory win — turning an int64 column that only holds small numbers into int16, or a repetitive str column into 'category', can shrink a frame dramatically.

Syntax

s.astype(dtype, errors='raise')

Examples

Python

import pandas as pd
print(pd.Series([1, 2, 3]).astype(float))

Output:

0    1.0
1    2.0
2    3.0
dtype: float64

Learn it in a lesson

See also

Back to the Dictionary