I have the following data frame, subsetted from my original data frame, with columns event, unixtime, and day, and I want to add another column arbday which is the nth day since the first event (with the first visit being day 1):
import numpy as np
import datetime as dt
>>> testdf = pd.DataFrame({'event': range(1,4), 'unixtime': [1346617885925, 1346961625305,1347214217566]},index=[343352,343353,343354])
>>> testdf['day'] = testdf['unixtime'].apply(lambda x: dt.datetime.utcfromtimestamp(x/1000).date())
event unixtime day arbday
343352 1 1346617885925 2012-09-02 1
343353 2 1346961625305 2012-09-06 5
343354 3 1347214217566 2012-09-09 8
After looking around, I tried to do this by:
>>> testdf2['arbday'] = np.where(testdf2['event']==1, 1, testdf2.day.apply(lambda x: x-x[:1]))
event unixtime day arbday
343352 1 1346617885925 2012-09-02 1
343353 2 1346961625305 2012-09-06 NaN
343354 3 1347214217566 2012-09-09 NaN
or
>>> testdf2['arbday'] = np.where(testdf2['event']==1, 1, testdf2.day.apply(lambda x: dt.timedelta(x-x[:1])))
TypeError: 'datetime.date' object is not subscriptable
What is the correct way to do this? Any pointer is much appreciated!
EDIT: A follow-up question regarding to applying this over groups is here.
output: