在熊猫数据框中删除少于 6 个月的重叠期

时间:2021-01-13 08:54:47

标签: python pandas dataframe

我有以下 Pandas 数据框,我想删除每个客户的日期差异小于 6 个月的每个客户的行。例如,我想为 ID 为 1 的客户保留以下日期 - 2017-07-01、2018-01-01、2018-08-01

Customer_ID    Date
1          2017-07-01
1          2017-08-01
1          2017-09-01
1          2017-10-01
1          2017-11-01
1          2017-12-01
1          2018-01-01
1          2018-02-01
1          2018-03-01
1          2018-04-01
1          2018-06-01
1          2018-08-01
2          2018-11-01     
2          2019-02-01
2          2019-03-01
2          2019-05-01
2          2020-02-01
2          2020-05-01

1 个答案:

答案 0 :(得分:3)

定义以下函数来处理每组行(针对每个客户):

def selDates(grp):
    res = []
    while grp.size > 0:
        stRow = grp.iloc[0]
        res.append(stRow)
        grp = grp[grp.Date >= stRow.Date + pd.DateOffset(months=6)]
    return pd.DataFrame(res)

然后将此函数应用于每个组:

result = df.groupby('Customer_ID', group_keys=False).apply(selDates)

对于您的数据样本,结果是:

    Customer_ID       Date
0             1 2017-07-01
6             1 2018-01-01
11            1 2018-08-01
12            2 2018-11-01
15            2 2019-05-01
16            2 2020-02-01