【发布时间】:2012-10-20 20:02:54
【问题描述】:
我有以下数据框,从我的原始数据框中子集,包含 event、unixtime 和 day 列,我想要添加另一列 arbday 这是自第一个事件以来的第 n 天(第一次访问是第 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
环顾四周后,我尝试这样做:
>>> 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
这样做的正确方法是什么?非常感谢任何指针!
编辑:关于在组上应用此功能的后续问题是here。
【问题讨论】: