apache-spark - 如何使用动态键加入 pyspark 数据框
问题描述
我有两个 spark DataFrame captureRate
,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'
捕获率:
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'
有什么指示我们可以像这样加入不相等的动态键吗?
解决方案
您不能使用这样的.
符号,但可以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"
)
看更多:
推荐阅读
- c++ - 用它的 processID 杀死一个进程
- css - SVG在没有脚本的情况下悬停n秒(工具提示的加载时间)后将光标从“cursor:wait”更改为“cursor:help”?
- nginx - 即使 url 中有 .php,如何将所有请求重定向到 index.php
- amazon-web-services - 我的免费套餐结束了吗?
- email - RFC 2822 格式 - 是否包含附件
- ios - tableView(_:heightForHeaderInSection:) 不工作
- haskell - `Functor`不是`Category`的超类是否有原因?
- ionic-framework - 我想在离子选择中选择离子选项后添加离子项目
- xml - 水壶(PDI)8.1读取xml错误
- scala - 在循环 DataFrame 并访问外部范围变量时获取 NullPointerException