[英]Pyspark subselect / subquery join using dataframes
我希望加入一個基於低於該值的最接近匹配的值。 在 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|
+----------+-----------+-----------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.