【发布时间】:2019-07-06 10:05:50
【问题描述】:
我一直在尝试使用以下作为列表传递的连接键列表来连接两个数据帧,如果其中一个键值为空,我想添加功能以加入键的子集
我一直在尝试加入两个数据帧 df_1 和 df_2。
data1 = [[1,'2018-07-31',215,'a'],
[2,'2018-07-30',None,'b'],
[3,'2017-10-28',201,'c']
]
df_1 = sqlCtx.createDataFrame(data1,
['application_number','application_dt','account_id','var1'])
和
data2 = [[1,'2018-07-31',215,'aaa'],
[2,'2018-07-30',None,'bbb'],
[3,'2017-10-28',201,'ccc']
]
df_2 = sqlCtx.createDataFrame(data2,
['application_number','application_dt','account_id','var2'])
我用来加入的代码是这样的:
key_a = ['application_number','application_dt','account_id']
new = df_1.join(df_2,key_a,'left')
同样的输出是:
+------------------+--------------+----------+----+----+
|application_number|application_dt|account_id|var1|var2|
+------------------+--------------+----------+----+----+
| 1| 2018-07-31| 215| a| aaa|
| 3| 2017-10-28| 201| c| ccc|
| 2| 2018-07-30| null| b|null|
+------------------+--------------+----------+----+----+
我担心的是,在 account_id 为空的情况下,连接应该仍然可以通过比较其他 2 个键来工作。
所需的输出应该是这样的:
+------------------+--------------+----------+----+----+
|application_number|application_dt|account_id|var1|var2|
+------------------+--------------+----------+----+----+
| 1| 2018-07-31| 215| a| aaa|
| 3| 2017-10-28| 201| c| ccc|
| 2| 2018-07-30| null| b| bbb|
+------------------+--------------+----------+----+----+
我发现了一种类似的方法,使用以下语句:
join_elem = "df_1.application_number ==
df_2.application_number|df_1.application_dt ==
df_2.application_dt|F.coalesce(df_1.account_id,F.lit(0)) ==
F.coalesce(df_2.account_id,F.lit(0))".split("|")
join_elem_column = [eval(x) for x in join_elem]
但设计考虑不允许我使用完全连接表达式,我坚持使用列名列表作为连接键。
我一直在尝试找到一种方法来将这个合并的东西融入这个列表本身,但到目前为止还没有发现任何成功。
【问题讨论】:
-
为什么不加入其他键然后过滤?
标签: python apache-spark join pyspark inner-join