Set days since first occurrence based on multiple columns

Viewed 42

I have a pandas dataset with this structure:

Date          datetime64[ns]
Events                 int64
Location              object
Day                  float64

I've used the following code to get the date of the first occurrence for location "A":

start_date = df[df['Location'] == 'A'][df.Events != 0].iat[0,0]

I now want to update all of the records after the start_date with the number of days since the start_date, where Day = df.Date - start_date.

I tried this code:

df.loc[df.Location == country, 'Day'] = (df.Date - start_date).days

However, that code returns an error:

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

The problem seems to be that the code recognizes df.Date as an object instead of a datetime. Anyone have any ideas on what is causing this problem?

1 Answers

Try, you need to add the .dt accessor.

df.loc[df.Location == country, 'Day'] = (df.Date - start_date).dt.days
Related