Python pandas Series.astype() Method

In this tutorial, we will learn the python pandas Series.astype() method. This method is used to convert the data type of the pandas' object. Using this method we can convert the datatype of the object to the specified datatype

The below shows the syntax of the Series.astype() method.

Syntax

Series.astype(dtype, copy=True, errors='raise')

Parameters

dtype: It is the data type or dict of the column name.

copy: It represents the bool(True or False), default is True. It returns a copy when copy=True

errors: It includes ‘raise’, ‘ignore’, and the default is ‘raise’

Example: Cast a pandas object using the Series.astype() method

Let's convert the Series object to another datatype using the Series.astype() method. Here, in this example, we converted from 'int64' to 'int32' datatype. See the below example.

import pandas as pd
series = pd.Series([1,2,3,4,5]) 
print("----Before converting datatype of DataFrame-----")
print(series.dtypes)
print("----After converting datatype of DataFrame-----")
print(series.astype('int32').dtypes)


----Before converting datatype of DataFrame-----
int64
----After converting datatype of DataFrame-----
int32

Example: Cast a pandas object using the Series.astype() method

This example is similar to the previous one. Let's convert the Series object to another datatype using the Series.astype() method. Here, in this example, we converted from 'int64' to 'str' datatype. See the below example.

import pandas as pd
series = pd.Series([1,2,3,4,5]) 
print("----Before converting datatype of DataFrame-----")
print(series.dtypes)
print("----After converting datatype of DataFrame-----")
print(series.astype(str).dtypes)


----Before converting datatype of DataFrame-----
int64
----After converting datatype of DataFrame-----
int32

Conclusion

In this tutorial, we learned the Python pandas Series.astype() method. We converted the datatype column of Series to another data type and checked the Series.