2

我有以下数据框,从我的原始数据框中子集,包含列eventunixtimeday,我想添加另一列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

4

1 回答 1

2
df = DataFrame({'event': range(1,4), 'unixtime': [1346617885925, 1346961625305,1347214217566]})
df['day'] = df['unixtime'].apply(lambda x: datetime.fromtimestamp(x/1000).date())
df['arbday']=df['day'].map(lambda x: (x-df.get_value(df[df.event == 1].first_valid_index(), 'day')).days+1)
print df

输出:

   event       unixtime         day  arbday
0      1  1346617885925  2012-09-02       1
1      2  1346961625305  2012-09-06       5
2      3  1347214217566  2012-09-09       8
于 2012-10-31T12:36:22.417 回答