PySpark:根据来自另一个数据框的日期范围过滤数据

如果位于和之间,我试图从df1 中选择记录(仅允许三个范围的 date2、date3 组合、逐行)。df1.date1df2.date2df2.date3


就我而言,没有共同的变量来建立“加入”标准。我尝试了不同的 pyspark.sql 函数,例如 'filter'、'when'、'withColumn'、'date_sub'、'date_add' 等,但无法找到解决方案。


我确实浏览了几篇 SO 帖子,但是,他们中的大多数建议使用“加入”,这可能不适合我的问题!


df1


+----------+-----------+

|  emp_id  |   date1   |

+----------+-----------+

|   67891  | 11-13-2015|

|   12345  | 02-28-2017|

|   34567  | 04-07-2017|

+----------+-----------+

df2


+------------+------------+

|  date2     |   date3    |

+------------+------------+

|01-28-2017  | 03-15-2017 |

|07-13-2017  | 11-13-2017 |

|06-07-2018  | 09-07-2018 |

+------------+------------+

预期记录:


+----------+-----------+

|  emp_id  |   date1   |

+----------+-----------+

|   12345  | 02-28-2017|

+----------+-----------+


明月笑刀无情
浏览 172回答 1
1回答

慕神8447489

您可以在 spark 中进行非对等连接。您不一定需要匹配的键。这是在scala中,我很确定它在python中几乎相同。让我知道它是否不起作用。也会更新 pyspark 中的答案。scala> df1.join(df2 , 'date1 > 'date2 && 'date1 < 'date3).show&nbsp; &nbsp; +------+----------+----------+----------+&nbsp; &nbsp; |emp_id|&nbsp; &nbsp; &nbsp;date1|&nbsp; &nbsp; &nbsp;date2|&nbsp; &nbsp; &nbsp;date3|&nbsp; &nbsp; +------+----------+----------+----------+&nbsp; &nbsp; | 12345|02-28-2017|01-28-2017|03-15-2017|&nbsp; &nbsp; +------+----------+----------+----------+Pyspark 解决方案:>>> from pyspark.sql.functions import unix_timestamp>>> from pyspark.sql.functions import from_unixtime>>> x = [(67891 ,'11-13-2015'),(12345, '02-28-2017'),(34567,'04-07-2017')]>>> df1 = spark.createDataFrame(x,['emp_id','date1'])>>> y = [('01-28-2017','03-15-2017'),('07-13-2017','11-13-2017'),('06-07-2018','09-07-2018')]>>> df2 = spark.createDataFrame(y,['date2','date3'])>>> df1a = df1.select('emp_id', from_unixtime(unix_timestamp('date1', 'MM-dd-yyy')).alias('date1'))>>> df2a = df2.select(from_unixtime(unix_timestamp('date2', 'MM-dd-yyy')).alias('date2'),from_unixtime(unix_timestamp('date3', 'MM-dd-yyy')).alias('date3'))>>> df1a.join(df2a, on=[df1a['date1'] > df2a['date2'], df1a['date1'] < df2a['date3']]).show()+------+-------------------+-------------------+-------------------+|emp_id|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; date1|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; date2|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; date3|+------+-------------------+-------------------+-------------------+| 12345|2017-02-28 00:00:00|2017-01-28 00:00:00|2017-03-15 00:00:00|+------+-------------------+-------------------+-------------------+
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python