python - 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)
解决方案
如果您提供更多关于您想要什么以及迄今为止尝试过的内容的详细信息,那将会更加有用。
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)
这与您提供的信息最匹配,并提供您正在寻找的输出。
推荐阅读
- angular - Angular 在 RTL 模式下的 UI-Grid,在水平滚动时显示缺失的列,并且列与相应单元格的水平对齐不正确
- ruby-on-rails - 为什么 I18n.locale 和 redirect_back 不起作用?
- javascript - 如何仅使用具有数字值的键返回对象?
- c++ - 是否可以替换 / 或 . 在宏中带有 __ 的字符串中?
- oracle-apex - apex_data_parser 文件 > 50MB
- python - 如何处理numpy中的nan值
- spring-cloud - 如何通过 Spring Cloud 数据流中的处理器应用程序触发组合任务运行程序?
- tabulator - 更新bottomCalc-value,基于选择(如果有的话)
- sql - INTERSECT ALL 不适用于 PostgreSQL 11
- c# - 为什么我不能从 linq 语句中的选择中删除列/道具