【发布时间】:2022-02-10 14:38:03
【问题描述】:
这是一个满足条件的示例。数据框 df1 和 df2 都有 id 列和 date 列。在 df1 中,id 列是唯一的,而在 df2 中,它是非唯一的。我想创建一个新的数据框,如果 df1.id == df2.id 并且 df2 中的某些日期对在 df1 中的日期的 1 周内,则发生连接
df1
| customer_id (unique) | 'purchase_date'|
| -------- | -------------- |
| 1 | 2021-05-14 |
| 2 | 2021-09-16 |
df2
| customer_id | 'visit_dates' |
| -------- | -------------- |
| 1 | 2021-05-11 |
| 1 | 2021-05-16 |
| 1 | 2021-05-21 |
| 2 | 2021-07-14 |
| 2 | 2021-09-17 |
# New Df will only have 1 row.
# For customer 1 there is a date within the range(05-07 -> 05-14)
# and within the range(05-14 -> 05-21) with matching id.
# For customer 2, there are no dates within (09-09 -> 09-16) so it should be filtered
newdf
| customer_id (unique) | 'purchase_date'| begin_date_range | end_date_range
| -------- | -------------- | ---------------- | -------------
| 1 | 2021-05-14 | 2021-05-11 | 2021-05-16
我了解如何在 SQL 中执行此操作,但我不知道哪些函数允许在 Pandas 中进行类似的日期谓词过滤。
构造df1和df2:
data1 = {'customer_id': [1, 2], 'purchase_date': ['2021-05-14', '2021-09-16']}
data2 = {'customer_id': [1, 1, 1, 2, 2],
'visit_dates': ['2021-05-11', '2021-05-16', '2021-05-21', '2021-07-14', '2021-09-17']}
【问题讨论】:
-
你能添加一些我们可以运行的
df = pd.DataFrame({...})语句来创建DataFrame吗?
标签: python pandas dataframe date