首页 > 解决方案 > 如何使用动态键加入 pyspark 数据框

问题描述

我有两个 spark DataFrame captureRatePatientCounts例如:

患者人数:

DataFrame[year_qtr: string, x: double, y: double, z: double]

或者

DataFrame[year_mon: string, x: double, y: double, z: double]

取决于timePeriod可能具有值的变量'year_qtr''year_mon'

捕获率:

DataFrame[product1: string, yr_qtr: string, vol: double, capt_rt: double]

或者

DataFrame[product1: string, yr_mon: string, vol: double, capt_rt: double]

基本上,这两种情况下的键都是动态的并且不同,我需要加入两个数据框,例如:

capturedPatients = (PatientCounts
                      .join(captureRate
                      ,PatientCounts.timePeriod == captureRate.yr_qtr
                      ,"left_outer")
                     )

这是一个错误

AttributeError: 'DataFrame' object has no attribute 'timePeriod'

有什么指示我们可以像这样加入不相等的动态键吗?

标签: apache-sparkdataframejoinpyspark

解决方案


您不能使用这样的.符号,但可以timePeriodgetItem(方括号)运算符一起使用。

由于captureRateDataFrame中对应的列略有不同,新建一个变量:

# turns "year_mon" into "yr_mon" and "year_qtr" into "yr_qtr"
timePeriodCapture = timePeriod.replace("year", "yr")  

capturedPatients = PatientCounts.join(
    captureRate, 
    on=PatientCounts[timePeriod] == captureRate[timePeriodCapture]
    how="left_outer"
)

或者,如果连接列始终位于相同的位置,您可以通过按索引访问列来创建连接条件:

capturedPatients = PatientCounts.join(
    captureRate, 
    on=PatientCounts[0] == captureRate[1], 
    how="left_outer"
)

看更多:


推荐阅读