Examples
Create a DataFrame:
import numpy as np
import pandas as pd
d = {'c1': [2, 3], 'c2': [4, 5]}
df = pd.DataFrame(data=d)
df.dtypes
Cast all columns to int32:
df.astype('int32').dtypes
Cast c1 to int32 using a dictionary:
df.astype({'c1': 'int32'}).dtypes
Create a series:
s = pd.Series([2, 3], dtype='int32')
s
s.astype('int64')
Convert to categorical type:
s.astype('category')
Convert to ordered categorical type with custom ordering:
cat_dtype = pd.api.types.CategoricalDtype(
categories=[3, 2], ordered=True)
s.astype(cat_dtype)
Using copy=False and changing data on a new pandas object may propagate changes:
s1 = pd.Series([2,3])
s2 = s1.astype('int64', copy=False)
s2[0] = 8
s1 # note that s1[0] has changed too