gpt4 book ai didi

python - Pandas df 中的日期范围。

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:44 24 4
gpt4 key购买 nike

我在索引中有一些日期,在 col2 中有其他日期,我正在尝试找到一种方法来找到与 col1 中的 col2 最接近的 2 个“括号”日期。这是一个例子。

[In]Dates
[Out]
Index col2
2065-12-20 2062-12-20
2061-10-31 2049-11-19
2045-11-28 2020-09-08
2043-10-31 2053-11-19
2040-07-30 2038-06-06
2049-06-30 2019-05-12
2036-01-31 2040-11-21

现在我希望对于我的第 2 列上的每个日期,我的索引中存在的最接近的上级日期以及我的索引中存在的最接近的下级日期也适用于我的第 2 列的每个日期。

[In] Find Bracket
[Out]
Index col2 High bracket low bracket
2065-12-20 2062-12-20 2065-12-20 2061-10-31
2061-10-31 2049-11-19 2061-10-31 2045-11-28
2045-11-28 2020-09-08 2020-09-08 2020-09-08
2043-10-31 2053-11-19 2061-10-31 2049-06-30
2040-07-30 2038-06-06 2040-07-30 2036-01-31
2049-06-30 2019-05-12 2036-01-31 2019-05-12
2036-01-31 2040-11-21 2043-10-31 2040-07-30
例如,

代表第一行。 2065-12-20 是索引中距 2062-12-20 (col2) 最接近的较高日期,索引中最接近的较低日期是 2061-10-31 等等...

我正在为此苦苦挣扎...我知道我需要使用 argmin() 并减去索引和 col2,但这样我只能找到一个,而不是同时更高和更低,这就是我的挣扎所在...

谢谢!

最佳答案

def find_closest(x, index_col):
min_diff = x - index_col.max()
last_val = index_col.max()
for val in list(index_col):
current_diff = x - val
if current_diff.days > min_diff.days and current_diff.days <= 0:
min_diff = current_diff
last_val = val
return last_val

在 col2 上应用此函数来查找高括号,类似地,您可以对 low_bracket 执行此操作。

根据我的理解,high_bracket 中 2020-09-08 的预期输出应该是 2036-01-31。

注意:为了实现此目的,我已将索引列转换为普通列。

关于python - Pandas df 中的日期范围。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43676330/

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