簡體   English   中英

在數據框中查找與多個條件匹配的第一個匹配項

[英]Find the first occurrence that matches multiple conditions in a dataframe

我有一個通用的日期和值數據框,我正在嘗試使用它創建另一個具有特定范圍的更過濾的數據框。

我很難找到第一次值等於或大於開始日期之后范圍的開始值的時間。

通用數據框:

             Value
Date               
2022-06-24     1302
2022-06-23     942
2022-06-22     346
2022-06-21     912
2022-06-17     245
2022-06-16     762
2022-06-15     899
2022-06-14     927
2022-06-13     234
2022-06-10     955
2022-06-09     1372

例如,在這種情況下,我想在我的一般數據框中找到第一個日期,其中一個值等於或大於起始值 (927),但在起始日期 (2022-06-14) 之后,所以, 2022 年 6 月 23 日。 (即值 (942) 大於起始值並且發生在范圍起始日期之后的第一個日期)。

Start Date   End Date  Start Value  End Value  First recurrence 
2022-06-14 2022-06-17          927        245        2022-06-23

編輯[1]:范圍是在代碼的其他部分(開始日期、結束日期、開始值、結束值),我只對第一次重復計算感興趣。

PS。 范圍的結構方式“第一次重復”總是在范圍之外。 所以不需要關心結束日期。

我已經嘗試了很多東西,但到目前為止,我的過濾數據幀的長度與一般數據幀的長度不同,我無法同時過濾日期和值。

這應該符合您的要求:

方法一:

x = df[(df.index > df2['Start Date'].iloc[0]) & (df.Value > df2['Start Value'].iloc[0])]
df2['First recurrence'] = x.index.min()

輸入:

df:
            Value
Date
2022-06-24   1302
2022-06-23    942
2022-06-22    346
2022-06-21    912
2022-06-17    245
2022-06-16    762
2022-06-15    899
2022-06-14    927
2022-06-13    234
2022-06-10    955
2022-06-09   1372

df2:
  Start Date   End Date  Start Value  End Value
0 2022-06-14 2022-06-17          927        245

輸出:

  Start Date   End Date  Start Value  End Value First recurrence
0 2022-06-14 2022-06-17          927        245       2022-06-23

方法二:

s = df2.squeeze()
x = df[(df.index > s['Start Date']) & (df.Value > s['Start Value'])]
df2['First recurrence'] = x.index.min()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM