我有两个spark DataFrames captureRate
和PatientCounts
,例如:
PatientCounts:
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'
captureRate:
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'
任何指针,我们如何才能在这样的不等动态键上联接?
答案 0 :(得分:0)
您不能像这样使用.
表示法,但是可以将timePeriod
与getItem
(方括号)运算符一起使用。
由于captureRate
DataFrame中的相应列略有不同,因此请创建一个新变量:
# 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"
)
查看更多: