python pandas:向量化时间序列窗口函数

时间:2017-11-29 23:35:51

标签: python pandas numpy vectorization

我有以下格式的pandas数据框:

'customer_id','transaction_dt','product','price','units'
1,2004-01-02,thing1,25,47
1,2004-01-17,thing2,150,8
2,2004-01-29,thing2,150,25
3,2017-07-15,thing3,55,17
3,2016-05-12,thing3,55,47
4,2012-02-23,thing2,150,22
4,2009-10-10,thing1,25,12
4,2014-04-04,thing2,150,2
5,2008-07-09,thing2,150,43

我写了以下内容来创建两个表示30天窗口的新字段:

import numpy as np
import pandas as pd

start_date_period = pd.period_range('2004-01-01', '12-31-2017', freq='30D')
end_date_period = pd.period_range('2004-01-30', '12-31-2017', freq='30D')

def find_window_start_date(x):
    window_start_date_idx = np.argmax(x < start_date_period.end_time)
    return start_date_period[window_start_date_idx]

df['window_start_dt'] = df['transaction_dt'].apply(find_window_start_date)

def find_window_end_date(x):
    window_end_date_idx = np.argmin(x > end_date_period.start_time)
    return end_date_period[window_end_date_idx]

df['window_end_dt'] = df['transaction_dt'].apply(find_window_end_date)

不幸的是,这对于我的应用程序的行申请来说太慢了。如果可能的话,我将非常感谢有关矢量化这些功能的任何提示。

修改

结果数据框应具有以下布局:

'customer_id','transaction_dt','product','price','units','window_start_dt','window_end_dt'

它不需要在正式意义上重新采样或加窗。它只需要添加'window_start_dt'和'window_end_dt'列。当前代码有效,如果可能,只需要进行矢量化。

1 个答案:

答案 0 :(得分:0)

编辑2 :内置pandas.cut

    tt=[[1,'2004-01-02',0.1,25,47],
[1,'2004-01-17',0.2,150,8],
[2,'2004-01-29',0.2,150,25],
[3,'2017-07-15',0.3,55,17],
[3,'2016-05-12',0.3,55,47],
[4,'2012-02-23',0.2,150,22],
[4,'2009-10-10',0.1,25,12],
[4,'2014-04-04',0.2,150,2],
[5,'2008-07-09',0.2,150,43]]



start_date_period = pd.date_range('2004-01-01', '12-01-2017', freq='MS')
end_date_period = pd.date_range('2004-01-30', '12-31-2017', freq='M')

df = pd.DataFrame(tt,columns=['customer_id','transaction_dt','product','price','units'])
df['transaction_dt'] = pd.Series([pd.to_datetime(sub_t[1],format='%Y-%m-%d') for sub_t in tt])

the_cut = pd.cut(df['transaction_dt'],bins=start_date_period,right=True,labels=False,include_lowest=True)

df['win_start_test'] = pd.Series([start_date_period[int(x)] if not np.isnan(x) else 0 for x in the_cut])
df['win_end_test'] = pd.Series([end_date_period[int(x)] if not np.isnan(x) else 0 for x in the_cut])

print(df.head())

win_start_testwin_end_test应该等于使用您的函数计算的对应项。

ValueError来自于未在相关行中投放xint。我还添加了NaN支票,但这个玩具示例并不需要。

请注意对pd.date_range的更改以及使用月初和月末标记MMS,以及将日期字符串转换为{ {1}}。