![](/img/trans.png)
[英]How to create a function that checks if one row in a PySpark column of a dataframe matches another row in the same column of another dataframe?
[英]How can I match two rows in a pyspark dataframe when the value in a column in a row matches the value in another column in another row?
我有一个如下的火花数据框。 如果col2中的值在col1的其他行中找到,我想在新列的列表中获取col3的值。 而且我宁愿不使用自我加入。
输入:
col1 col2 col3
A B 1
B C 2
B A 3
输出:
col1 col2 col3 col4
A B 1 [2,3]
B C 2 []
B A 3 [1]
您需要使用groupby
创建映射,然后使用merge
。
mapper = df.groupby('col1', as_index=False).agg({'col3': list}).rename(columns={'col3':'col4', 'col1': 'col2'})
df.merge(mapper, on='col2', how='left')
输出:
col1 col2 col3 col4
0 A B 1 [2, 3]
1 B C 2 NaN
2 B A 3 [1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.