Zee
Zee

Reputation: 91

Python Convert datetime to int for training model

I am trying to convert [timedelta64[ns]] dtype to int as I want to start training the model but i keep getting the following error: TypeError:cannot astype a timedelta from [timedelta64[ns]] to [float64]

I need to convert it to a number dtype before training it, correct?

edit: I have a dataset and the Y predictor is datatype [timedelta64[ns]] where it predicts how many days a given records day shift was:

X columns (all columns have been converted to numbers through one hot encoder as some were categorical) Role Type Phase Bid Value

Y column Dateshift 20 days 15 days 10 days

So do I need to convert the Y column into int before training the model? If so, how?

Upvotes: 0

Views: 778

Answers (2)

CHRD
CHRD

Reputation: 1957

You can convert a timedelta to float64 by converting to int first like this:

df['new'] = df.timedelta_column.astype('int').astype('float64')

If the end goal is to get the number of days:

df['new'] = df.timedelta_column.dt.days

EDIT: Based on the comments, if you want to use the float64 value and then bring it back to timedelta for interpretation:

df['new_float'] = df.timedelta_column.astype('int').astype('float64')
df['new_timedelta'] = pd.to_timedelta(df['new_float'])

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

You can divide timedelta, for example:

df['timedelta_col'] = df['timedelta_col'] / pd.to_timedelta('1D')

Upvotes: 1

Related Questions