我有两个具有相同模式且具有500多列的sql数据帧:
df_A
+----+---+---+...
| id | A | B |...
+----+---+---+...
| w1 | 0 | 1 |...
+----+-- +---+...
| w2 | 1 | 1 |...
+----+-- +---+...
| w3 | 0 | 1 |...
+----+-- +---+...
df_B
+----+---+---+...
| id | A | B |...
+----+---+---+...
| w1 | 0 | 1 |...
+----+-- +---+...
| w2 | 0 | 1 |...
+----+-- +---+...
| w3 | 0 | 1 |...
+----+-- +---+...
我想返回一个数据帧,这样当df_A时。是1然后是1,否则是df_B的值。
以下代码能够正确返回列比较,但我无法添加id列。有什么建议吗?
results = df_A.alias("a").join(df_B.alias("b"), "id").selectExpr(["case when b.`{0}` = 1 then 1 else a.`{0}` end as `{0}`".format(yy) for yy in df_b.columns[1:]])
答案 0 :(得分:2)
在此,您只想在"Master_ID"
中选择selectExpr()
。但是因为剩下的args是作为列表构建的,所以你不能这样做。也将它传递给列表旁边。您将要将其添加到列表中,例如:
select_exprs = [...]
select_exprs.append("Master_ID")
....selectExpr(select_exprs)
或更完整:
column_select = ["Master_ID"]
select_expr = ["case when b.`{0}` = 1 then 1 else a.`{0}` end as `{0}`".format(yy) for yy in prediction_df.columns[1:]]
column_select = column_select + select_expr
results = wide_pred_df.alias("a").join(prediction_df.alias("b"),"Master_ID").selectExpr(column_select)
results.printSchema