[英]Filtering based on date ranges from another dataframe
I have two pandas dataframes as following:我有两个 pandas 数据帧如下:
df1: df1:
id date item
3 2015-11-23 B
3 2015-11-23 A
3 2016-05-11 C
3 2017-02-01 C
3 2018-07-12 E
4 2014-05-11 C
4 2015-02-01 C
4 2018-07-12 E
df2 df2
id start end
3 2016-05-11 2017-08-30
4 2015-01-11 2017-08-22
I would like to cut df1 such that I only keep items of df1 which falls within the date ranges given in df2 :我想削减df1这样我只保留属于df2中给出的日期范围内的 df1 项目:
id date item
3 2016-05-11 C
3 2017-02-01 C
4 2015-02-01 C
In reality, df1 and df2 are of millions of rows and therefore, I won't be able to do any quick fixes using for loops for example.实际上,df1 和 df2 有数百万行,因此,我无法使用 for 循环等进行任何快速修复。 I have rough idea of using groupby by id, but I am afraid all my tries have failed so far.
我有按 id 使用 groupby 的粗略想法,但恐怕到目前为止我所有的尝试都失败了。
Thank you in advance!先感谢您!
The basic way is to build a dataframe containing all possible events for that id
.基本方法是构建一个 dataframe ,其中包含该
id
的所有可能事件。 You can then filter on whether that event is between your two dates.然后您可以过滤该事件是否在您的两个日期之间。
df3 = df1.merge(df2, how='inner', left_on='id', right_on='id')
df3[(df3['date'] <= df3['end']) & (df3['date'] >= df3['date'])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.