大Pandas的日期范围。

2024-04-27 03:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在索引中有一些日期,在col2中有一些日期,我正在试图找到一种方法,从col1中的col2中找到两个最接近的“括号”日期。下面是一个例子。你知道吗

[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()和substract index和col2,但是这样我就可以找到一个,而不是一个高一个低,这就是我的困惑所在。。。你知道吗

谢谢你!你知道吗


Tags: 方法inindexfind指数out例子col2
1条回答
网友
1楼 · 发布于 2024-04-27 03:22:36
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上应用这个函数来查找高位括号,同样地,也可以对低位括号执行此操作。你知道吗

据我所知,贵公司预计2020-09-08年的高产量应为2036-01-31。你知道吗

注意:为了实现这一点,我将索引列转换为普通列。你知道吗

相关问题 更多 >