Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'Series' object has no attribute 'days'

I have a column 'delta' in a dataframe dtype: timedelta64[ns], calculated by subcontracting one date from another. I am trying to return the number of days as a float by using this code:

from datetime import datetime
from datetime import date
df['days'] = float(df['delta'].days)

but I receive this error:

AttributeError: 'Series' object has no attribute 'days'

Any ideas why?

like image 368
OllieP Avatar asked Jul 07 '17 22:07

OllieP


2 Answers

DataFrame column is a Series, and for Series you need dt.accessor to calculate days (if you are using a newer Pandas version). You can see docs here

So, you need to change:

df['days'] = float(df['delta'].days)

To

df['days'] = float(df['delta'].dt.days)
like image 144
Aseem Ahir Avatar answered Oct 10 '22 04:10

Aseem Ahir


While subtracting the dates you should use the following code.

df = pd.DataFrame([ pd.Timestamp('20010101'), pd.Timestamp('20040605') ])
(df.loc[0]-df.loc[1]).astype('timedelta64[D]')

So basically use .astype('timedelta64[D]') on the subtracted column.

like image 26
howard roark Avatar answered Oct 10 '22 06:10

howard roark