我在 for 循环中比较了两个数据帧:df_intervals
和 df_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]
答案 0 :(得分:2)
也许您应该研究列表理解以及 any
和 all
函数。此外,如果您查看内部循环的主体,则那里有 if/else
条件,它要么是 break
要么是 continue
。所以最后一行无法访问。
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))
答案 1 :(得分:1)
除了 coreyp_1 的回答之外,您的匹配在每个间隔开始时都设置为 False,而不是您想要的每个事件。
答案 2 :(得分:0)
你的最后一个
matches.append(match)
可能缩进太深了一级。就像现在一样,由于前面的 break
块的 continue
和 if..else
,该行永远不会执行。