gpt4 book ai didi

python - 在 python 中过滤日期列表的列表

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:57 26 4
gpt4 key购买 nike

我有以下列表:

[[Timestamp('2018-04-07 00:00:00'), Timestamp('2018-07-07 00:00:00'),Timestamp('2020-04-07 00:00:00')], [Timestamp('2018-04-07 00:00:00'),Timestamp('2018-10-07 00:00:00'),Timestamp('2018-12-07 00:00:00'),Timestamp('2021-04-07 00:00:00'),Timestamp('2022-04-07 00:00:00'),Timestamp('2023-04-07 00:00:00')]

我的问题是是否可以按另一个日期过滤列表列表。例如:如果我选择这个日期:

datetime.datetime(2019, 1, 26, 0, 0)

有没有一种方法可以过滤列表的列表,只选择那些早于我选择的日期以及我的日期之前的最后一个日期的日期?例如,对于列表的第一个列表,我想保留值:

[Timestamp('2018-07-07 00:00:00'),Timestamp('2020-04-07 00:00:00')]

对于列表列表的第二个列表:

[Timestamp('2018-12-07 00:00:00'),Timestamp('2021-04-07 00:00:00'),Timestamp('2022-04-07 00:00:00'),Timestamp('2023-04-07 00:00:00')]   

最佳答案

是这样的吗?

import datetime
from pandas import Timestamp


# List of Timestamps
list_of_dates = [[Timestamp('2018-04-07 00:00:00'), Timestamp('2018-07-07 00:00:00'), Timestamp('2020-04-07 00:00:00')], [Timestamp('2018-04-07 00:00:00'), Timestamp('2018-10-07 00:00:00'), Timestamp('2018-12-07 00:00:00'), Timestamp('2021-04-07 00:00:00'), Timestamp('2022-04-07 00:00:00'), Timestamp('2023-04-07 00:00:00')]]

# Target date that we use as filter
target_date = datetime.datetime(2019, 1, 26, 0, 0)

def filter_dates(date_list, target_date):
"""Filter given timestamps according to target date.

Keep last date before target date and all future dates after target date."""

# Initialise return list
filtered_dates = []

# Iterate over list of lists
for dates in date_list:

# Use list comprehension to filter dates that are on either sides of the target date
dates_before_target_date = [date for date in dates if date < target_date]
dates_after_target_date = [date for date in dates if date > target_date]

# Keep last date before the target date and all future dates
filtered_dates.append([dates_before_target_date[-1]] + dates_after_target_date)

return filtered_dates

filtered_dates = filter_dates(list_of_dates, target_date)
print(filtered_dates)

这产生

[
[Timestamp('2018-07-07 00:00:00'), Timestamp('2020-04-07 00:00:00')],
[Timestamp('2018-12-07 00:00:00'), Timestamp('2021-04-07 00:00:00'), Timestamp('2022-04-07 00:00:00'), Timestamp('2023-04-07 00:00:00')]
]

关于python - 在 python 中过滤日期列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53318697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com