Signature
DataFrame.astype(dtype, copy=True)What it does
astype casts values to a chosen type. Convert category codes to numeric types before models that require numbers, and use nullable pandas dtypes such as Int64 when missing values must survive an integer conversion.
Parameters
dtypedtype or dict- Target dtype or a mapping from column to dtype.
copybool, optionaloptional- Return a copy even when no conversion is needed.
Returns
DataFrame
Example
pythonDataFrame.astype example
import pandas as pd
df = pd.DataFrame({"code": ["1", "2", "3"]})
print(df.astype({"code": "int64"}).dtypes)Output
code int64 dtype: object
Watch out for
- astype fails on missing values when the target is a plain int dtype.
- Casting a category to int uses the category codes, not the label text.