pandas.DataFrame.astype() Function example in python

Spread the love

pandas.DataFrame.astype(): This function cast a pandas object to a specified dtype dtype.

Syntax: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)

Parameters:
dtype : data type, or dict of column name -> data type
Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.

copy : bool, default True
Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects).

errors : {‘raise’, ‘ignore’}, default ‘raise’
Control raising of exceptions on invalid data for provided dtype.

raise : allow exceptions to be raised
ignore : suppress exceptions. On error return original object
New in version 0.20.0.

kwargs : keyword arguments to pass on to the constructor
Returns:
casted : same type as caller

import pandas as pd d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) print(df.dtypes) df2=df.astype('float64') print(df2.dtypes)

Output:

col1 int64
col2 int64
dtype: object
col1 float64
col2 float64
dtype: object