首页 > 解决方案 > Python 在 180 天内删除重复项

问题描述

我有一个如下所示的数据框(即df)。如果日期在前一条记录的 180 天内,我想删除重复的名称。dfa 中的期望结果

欣赏建议。谢谢。

我有的数据

import pandas as pd
 
dict = {'Name':['John','John','John','John','John','John','Peter','Peter','Luke','Luke'],'Date':['2021-03-01', '2021-08-01','2021-12-01', '2022-04-11', '2022-10-01','2023-12-01','2021-05-01','2021-12-31','2021-08-01','2021-11-01']}
       
df=pd.DataFrame(dict)

期望的结果

dict_answer = {'Name':['John','John','John','John','Peter','Peter','Luke'],'Date':['2021-03-01','2021-12-01', '2022-10-01','2023-12-01','2021-05-01','2021-12-31','2021-08-01']}
 
dfa=pd.DataFrame(dict_answer)

标签: python

解决方案


如果您提供更多关于您想要什么以及迄今为止尝试过的内容的详细信息,那将会更加有用。

from datetime import datetime

dictionary = {'Name': ['John', 'John', 'John', 'John', 'John', 'John', 'Peter', 'Peter', 'Luke', 'Luke'],
              'Date': ['2021-03-01', '2021-08-01', '2021-12-01', '2022-04-11', '2022-10-01', '2023-12-01', '2021-05-01',
                       '2021-12-31', '2021-08-01', '2021-11-01']}

df = pd.DataFrame(dict)
names = dictionary['Name']
dates = dictionary['Date']

dict_answer = {'Name': [], 'Date': []}

while names:
    if names[0] not in dict_answer['Name']:
        dict_answer['Name'].append(names[0])
        names.pop(0)

        dict_answer['Date'].append(dates[0])
        dates.pop(0)
        continue
    elif names[0] == dict_answer['Name'][-1]:
        d1 = datetime.strptime(dict_answer['Date'][-1], "%Y-%m-%d")
        d2 = datetime.strptime(dates[0], "%Y-%m-%d")
        delta = d2 - d1
        if delta.days > 180:
            dict_answer['Name'].append(names[0])
            names.pop(0)

            dict_answer['Date'].append(dates[0])
            dates.pop(0)
            continue
        else:
            names.pop(0)
            dates.pop(0)

dfa = pd.DataFrame(dict_answer)

这与您提供的信息最匹配,并提供您正在寻找的输出。


推荐阅读