python - 使用数据框的 Pyspark 子选择/子查询连接
问题描述
我希望加入一个基于低于该值的最接近匹配的值。在 SQL 中,我可以很容易地做到这一点。考虑以下数据:
tbl 实际值
|Date |Temperature:
|09/02/2020 |14.1
|10/02/2020 |15.3
|11/02/2020 |12.2
|12/02/2020 |12.4
|13/02/2020 |12.5
|14/02/2020 |11
|15/02/2020 |14.6
tbl系数:
|Metric |Coefficient
|10.5 |0.997825593
|11 |0.997825593
|11.5 |0.997663198
|12 |0.997307614
|12.5 |0.996848773
|13 |0.996468537
|13.5 |0.99638519
|14 |0.996726301
|14.5 |0.997435894
|15 |0.998311153
|15.5 |0.999135509
在 SQL 中,我可以通过以下方式实现加入:
Select
a.date,
b.temperature,
(select top 1 b.Coefficient from tblCoefficients b where b.Metric <= a.Temperature order by b.Metric desc) as coefficient
from tblActuals
有没有办法用两个 pyspark 数据帧中的数据实现与上述相同的效果?我可以在 spark SQL 中获得类似的结果,但我需要数据帧的灵活性来实现我在数据块中创建的过程。
解决方案
您可以进行连接并获取最大(最接近)指标的系数:
import pyspark.sql.functions as F
result = tblActuals.join(
tblCoefficients,
tblActuals['Temperature'] >= tblCoefficients['Metric']
).groupBy(tblActuals.columns).agg(
F.max(F.struct('Metric', 'Coefficient'))['Coefficient'].alias('coefficient')
)
result.show()
+----------+-----------+-----------+
| Date|Temperature|coefficient|
+----------+-----------+-----------+
|15/02/2020| 14.6|0.997435894|
|12/02/2020| 12.4|0.997307614|
|14/02/2020| 11.0|0.997825593|
|13/02/2020| 12.5|0.996848773|
|11/02/2020| 12.2|0.997307614|
|10/02/2020| 15.3|0.998311153|
|09/02/2020| 14.1|0.996726301|
+----------+-----------+-----------+
推荐阅读
- jquery - jquery.repeater 使用 setList 函数渲染多个组时存在问题
- java - WSDL 文件到 Jar 文件
- reactjs - React hooks:如何在类组件中在构造函数中初始化的功能组件中编写变量
- gluon-mobile - 如何在 Gluon 移动应用上实现 JWT
- jquery - 仅针对特定类的一个元素的 JQuery 事件
- typo3 - 在 Typo3 代码中提交表单时出错:201905310232036dfcc153
- python - 如何训练神经网络来识别书面和口头数字是否相同
- amazon-web-services - 在域下创建子域并将该域用于电子邮件票务服务
- jenkins - 如何在 Jenkins 上正确地将 TFS 变更集编号放入 SonarScanner 的项目版本字段中?
- android - 如何管理来自特定不同活动的 NFC 标签读取