close

[Solved] cannot convert the series to

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error cannot convert the series to <class ‘int’`> in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How cannot convert the series to <class ‘int’`> Error Occurs?

Today I get the following error cannot convert the series to <class ‘int’`> in python.

How To Solve cannot convert the series to <class ‘int’`> Error ?

  1. How To Solve cannot convert the series to Error ?

    To Solve cannot convert the series to <class 'int'`> Error Your error is line 2. df['intage'] = int(df['age']) is not valid, you can't pass a pandas series to the int function.

  2. cannot convert the series to

    To Solve cannot convert the series to <class 'int'`> Error Your error is line 2. df['intage'] = int(df['age']) is not valid, you can't pass a pandas series to the int function.

Solution 1

Your error is line 2. df['intage'] = int(df['age']) is not valid, you can’t pass a pandas series to the int function.

You need to use astype if df[‘age’] is object dtype.

df['intage'] = df['age'].astype(int)

Or since you are subtracting two dates, you need to use dt accessor with the days attribute to get the number of days as an integer

df['intage'] = df['age'].dt.days

Solution 2

Since the dtype is timedelta64[ns] you can either use between, specifying two timedeltas as the endpoints, or you can first convert the days to a numeric type using numpy.

Setup

import pandas as pd
import numpy as np

df = pd.DataFrame({'age': [83, 108, 83, 63, 81]})
df['age'] = pd.to_timedelta(df.age, unit='days')

Find those between 82 and 107 days:

df[df.age.between(pd.to_timedelta(82, unit='days'), pd.to_timedelta(107, unit='days'))]
#      age
#0 83 days
#2 83 days

With numpy

df[(df.age/np.timedelta64(1, 'D')).between(82, 107)]
#      age
#0 83 days
#2 83 days

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read