Skip to main content
 首页 » 编程设计

python之如何比较非相同标记的 Pandas 数据框对象中的值

2024年10月01日18mfryf

我有两个具有不同标签的数据帧,df1 和 df2。

df1 包含(除其他事项外)时间间隔列表(开始/停止)。 df2 包含带有时间戳的事件列表。

我想检查 df1 中的哪些时间间隔包含来自 df2 的事件。具体是哪一个事件并不重要,多少个事件也不重要。是/否就足够了。

我有什么(简化):

df1

 Index  Start_time  Stop_time (other columns...) 
 1      1           5 
 2      8           10 
 3      20          22 
 4      23          40 

df2

Index  Event_time (other columns...) 
1      2 
2      400 
3      21 
4      40 

我想要什么:

df3

 Index  Start_time  Stop_time Event Event_time(optional) (other columns...) 
 1      1           5         Yes   2 
 2      8           10        No    NaN 
 3      20          22        Yes   21 
 4      23          40        Yes   40 

请注意,(其他列)在两个数据框中是不同的。因此,直接比较会产生Can only compare identically-labeled DataFrame objects错误。

如何比较非相同标记的 pandas 数据框对象中的值?

编辑:This和 this看起来它适用于这里,但目前没有结果

请您参考如下方法:

考虑使用 series between :

df = df[df['event_time'].between(<Start_time>, <Stop_time>, inclusive=True)] 

编辑:

In [151] 
df1  = pd.DataFrame({'Start_time':[1,8,20,23], 'Stop_time':[5,10,22,40]}) 
 
In [152] 
df2 = pd.DataFrame({'Event_time':[2, 400, 21, 40]}) 
 
In [153] 
df2['Event'] = df2['Event_time'].between(df1['Start_time'], df1['Stop_time'], inclusive=True) 
 
In [154] 
df2 
Out [154]: 
   Event_time  Event 
0           2   True 
1         400  False 
2          21   True 
3          40   True