如何比较非同一标签的pandas数据帧对象中的值?

时间:2017-02-01 11:53:00

标签: python pandas numpy

我有两个带有不同标签的数据框,df1df2

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数据框对象中的值?

编辑:Thisthis看似适用于此处,但到目前为止没有结果

1 个答案:

答案 0 :(得分:2)

考虑使用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