【发布时间】:2020-06-24 18:38:42
【问题描述】:
这是我的交易数据:
id from_id to_id amount date_trx
<fctr> <fctr> <fctr> <dbl> <date>
0 7468 5695 700.0 2005-01-04
1 6213 9379 11832.0 2005-01-08
2 7517 8170 1000.0 2005-01-10
3 6143 9845 4276.0 2005-01-12
4 6254 9640 200.0 2005-01-14
5 6669 5815 200.0 2005-01-20
6 6934 8583 49752.0 2005-01-24
7 9240 8314 19961.0 2005-01-26
8 6374 8865 1000.0 2005-01-30
9 6143 6530 13.4 2005-01-31
...
我想根据时间间隔构建新功能。
让我们看看这个:
id from_id to_id amount date_trx
<fctr> <fctr> <fctr> <dbl> <date>
149431 5370 5735 1000.0 2007-03-24
157403 5370 7058 3679.0 2007-04-13
158831 5370 8667 12600.0 2007-04-23
162680 5370 6053 19.2 2007-04-30
167082 5370 8165 3679.0 2007-05-13
168562 5370 5656 2100.0 2007-05-23
172578 5370 5929 79.0 2007-05-31
177507 5370 6725 3679.0 2007-06-01
179167 5370 8433 200.0 2007-06-22
183499 5370 7022 100.6 2007-06-29
...
假设我想计算每个帐户的交易金额,例如,以周为单位。
所以,从2007-03-24开始,5370的每周交易金额历史如下:
in the 1st week(2007-03-24 - 2007-03-31): 1000.0
in the 2nd week(2007-03-31 - 2007-04-07): 0.0
in the 3rd week(2007-04-07 - 2007-04-14): 3679.0
in the 4th week(2007-04-14 - 2007-04-21): 0.0
in the 5th week(2007-04-21 - 2007-04-28): 12600.0
in the 6th week(2007-04-28 - 2007-05-05): 19.2
in the 7th week(2007-05-05 - 2007-05-12): 0.0
in the 8th week(2007-05-12 - 2007-05-19): 3679.0
in the 9th week(2007-05-19 - 2007-05-26): 2100.0
in the 10th week(2007-05-26 - 2007-06-02): 79.0 + 3679.0 = 3758.0
in the 11th week(2007-06-02 - 2007-06-09): 0.0
in the 12th week(2007-06-09 - 2007-06-16): 0.0
in the 13th week(2007-06-16 - 2007-06-23): 200.0
in the 14th week(2007-06-23 - 2007-06-30): 100.6
在这里,我们看到一周内交易的最大金额 5370 是 12600.0。所以,现在我想将此度量视为一项功能,例如max_of_weekly_transacted_amount。
同样,我想计算每个帐户在一个月内的平均交易量并将其存储为另一个特征,例如mean_of_monthly_transacted_amount
我试过润滑函数floor_date:
# Max of weekly transaction amount
data <- data %>% group_by(date_trx_week=floor_date(date_trx, "week"),from_id) %>% mutate(weekly_trx = sum(amount)) %>%
group_by(from_id) %>% mutate(max_of_weekly_transacted_amount=max(weekly_trx))%>%
select(-c(date_trx_week,weekly_trx))
# Mean of monthly transaction amount
data <- data %>% group_by(date_trx_month=floor_date(date_trx, "month"),from_id) %>% mutate(monthly_trx = sum(amount)) %>%
group_by(from_id) %>% mutate(mean_of_monthly_transacted_amount=mean(monthly_trx))%>%
select(-c(date_trx_month,monthly_trx))
我的数据中的日期变量date_trx 以2005-01-01 开头,以2010-12-31 结尾。 floor_date 以 2005-01-02-2005-01-09 开始周期间,并以 2005-01-09-2005-01-16 继续,依此类推。它以2005-01-01-2005-02-01 开始月份,并以2005-02-01-2005-03-01 继续,依此类推。此函数对每个帐户使用相同的期间。
但我想根据每个帐户的第一个交易日期专门为每个帐户制作期间。所以,对于from_id = 5370,第一个交易日期是2007-03-24。如果我想为5370 创建周期间,则为2007-03-24 - 2007-03-31、2007-03-31 - 2007-04-07 等等。如果我想为5370 设置月份,那就是2007-03-24 - 2007-04-24、2007-04-24 - 2007-05-24,等等。
对于另一个帐户,期间会有所不同。那么,我该如何实现呢?如何从每个帐户的第一个交易日期开始分别为每个帐户设置特定期间?
【问题讨论】:
标签: r date aggregate lubridate feature-engineering