【问题标题】:Moving to next iteration in nested for loop if condition met如果满足条件,则移动到嵌套 for 循环中的下一次迭代
【发布时间】:2021-05-15 15:43:07
【问题描述】:

我有两个要在 for 循环中比较的数据框:df_intervalsdf_events。对于每个事件,循环检查事件的时间戳是否落在所有可能的时间间隔之间。我打算让循环对每个事件进行检查,检查每个间隔,如果为 True,则附加到列表并继续下一个,如果全部为 False,则将 False 附加到列表。

df_events, df_intervals

(  Var2                  ts
 0  bar 2021-02-10 09:04:31
 1  bar 2021-01-29 05:56:17
 2  bar 2021-01-16 15:59:43
 3  bar 2021-01-25 09:40:40
 4  bar 2021-01-27 16:44:57
 5  bar 2021-01-17 13:28:43
 6  bar 2021-02-03 11:46:10
 7  bar 2021-02-02 11:16:49
 8  bar 2021-01-21 17:12:15
 9  bar 2021-01-19 03:44:30,
   Var1            start_ts              end_ts
 0  foo 2021-02-01 20:29:57 2021-02-02 20:29:57
 1  foo 2021-02-03 20:29:57 2021-02-04 20:29:57
 2  foo 2021-02-04 20:29:57 2021-02-05 20:29:57
 3  foo 2021-02-05 20:29:57 2021-02-06 20:29:57
 4  foo 2021-02-06 20:29:57 2021-02-07 20:29:57
 5  foo 2021-02-07 20:29:57 2021-02-08 20:29:57
 6  foo 2021-02-08 20:29:57 2021-02-11 20:29:57
 7  foo 2021-02-08 20:29:57 2021-02-10 20:29:57
 8  foo 2021-02-10 20:29:57 2021-02-11 20:29:57)

我不确定我在这里做错了什么,因为我在每个事件的开头设置match=False,如果不满足条件,则将其附加到循环末尾的列表中。

matches = []
for event in df_events['ts']:
    for idx, a,b,c in df_intervals.itertuples():
        match=False
        if b <= event <= c:
            match=True
            matches.append(match)
            break
        else:
            continue
        matches.append(match)
​

matches
matches
[True, True]

想要的输出是:

[True, False, False, False, False, False, False, True, False, False]

【问题讨论】:

    标签: python pandas list for-loop


    【解决方案1】:

    也许你应该研究一下列表理解和anyall 函数。此外,如果您查看内部循环的主体,则那里有if/else 条件,它要么是breaks,要么是continues。所以最后一行是无法到达的。

    def find_matches(events, intervals):
        for event in events['ts']:
            if any(start <= event and event <= end
                   for _, _, start, end in intervals.itertuples()):
                yield True
            else:
                yield False
    
    matches = list(find_matches(df_event, df_intervals))
    

    【讨论】:

    • return 和 yield 有什么区别?
    • 我看到它的方式是在主体中带有 yield 关键字的函数返回一个生成器对象,它本身是可迭代的,在 for 循环和其他地方,很容易转换为列表。
    【解决方案2】:

    除了 coreyp_1 的回答之外,您的匹配在每个间隔开始时设置为 False,而不是您想要的每个事件。

    【讨论】:

      【解决方案3】:

      你的最后一个

      matches.append(match)
      

      可能缩进了一层太深。现在,由于前面的 if..else 块的 breakcontinue,该行将永远不会执行。

      【讨论】:

        猜你喜欢
        • 2017-10-05
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 2020-06-16
        • 2020-02-20
        • 2014-11-11
        • 2019-11-23
        • 1970-01-01
        相关资源
        最近更新 更多