How does pandas series astype() method work?


In the pandas series, the astype() method is used to convert the data type of the pandas series object. And the astype() method will return a series object with the converted data type.

Using this astype() method in pandas.Series we can convert the datatype of the series object to the specified data type, to achieve this, we need to send a numpy.dtype or Python type as a parameter to the astype() method.

Example 1

# importing required packages
import pandas as pd

# create a pandas Series object
series = pd.Series([1,2,4,3,1,2])
print(series)

result = series.astype('category')
print("Output: ",result)

Explanation

In this example, we have initialized a pandas series object with a list of integer values. after that, we applied the astype() method with a parameter value “category”.

Output

0 1
1 2
2 4
3 3
4 1
5 2
dtype: int64

Output:
0 1
1 2
2 4
3 3
4 1
5 2
dtype: category
Categories (4, int64): [1, 2, 3, 4]

In this output block, we can see the initial series object with data type int64 and the output of the astype() method with the converted datatype. The data type of the resultant series object is a category. There 4 categorical values are available in the resultant series object.

Example 2

# importing required packages
import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series(np.random.randint(1,20,5))
print(series)

# change the astype
result = series.astype('float64')
print("Output: ",result)

Explanation

Create another pandas series object with random integer values of range 1,20,5. Here the goal is to cast the data type of the original series object to the “float64” type so that the astype() method is applied to the series object with the “float64” parameter.

Output

0 15
1  2
2 10
3  1
4 15
dtype: int32

Output:
0 15.0
1  2.0
2 10.0
3  1.0
4 15.0
dtype: float64

For the original series object the dtype is “int32”, and the converted series object is having a float64 data type.

Updated on: 09-Mar-2022

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements