【问题标题】:How to join in pyspark dataframe with dynamic keys如何使用动态键加入 pyspark 数据框
【发布时间】:2019-11-25 14:50:14
【问题描述】:

我有两个 spark DataFrames 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'

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

【问题讨论】:

  • 您能在这种情况下更具体地了解动态键吗?
  • 如果连接列总是在相同的位置,你应该可以根据位置列进行连接:PatientCounts.join(captureRate, on=PatientCounts[0] == captureRate[1], how="left_outer")

标签: apache-spark dataframe join pyspark


【解决方案1】:

您不能像那样使用. 表示法,但可以将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"
)

查看更多:

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2023-03-12
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2022-01-23
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多