繁体   English   中英

如何通过 pyspark 中的列向另一个数据帧中的数据帧添加行

[英]how to add rows to a data frame that are in another data frame by a column in pyspark

我有 2 个 dfs,我想将第二个 df 中的行移到第一个。 但我只想在 cid 列中的值不在第一行时添加这些行。

df1
x  y  z  cid
4  8  1  1
7  5  6  2
7  3  5  3

df2
x  y  z  cid
8  4  5  1
1  2  9  2
8  6  4  3
4  5  4  4

result:
x  y  z  cid
4  8  1  1
7  5  6  2
7  3  5  3
4  5  4  4

你可以试试下面的代码。

from pyspark.sql.functions import *
# Create DataFrame df1
df1 = spark.createDataFrame([(4,8,1,1), (7,5,6,2), (7,3,5,3)], ["x", "y", "z", "cid"])

# Create DataFrame df2
df2 = spark.createDataFrame([(8,4,5,1), (1,2,9,2), (8,6,4,3), (4,5,4,4)], ["x", "y", "z", "cid"])

# Get the values from cid column from df1
col1 = df1.select(collect_set("cid")).collect()[0][0]

# Filter the dataframe df2 where cid values present in df2 but not in df1.
df3 = df2.filter(~df2["cid"].isin(col1))

# Union df1 and df3.
df4 = df1.union(df3)
df4.show()

// Output

+---+---+---+---+
|  x|  y|  z|cid|
+---+---+---+---+
|  4|  8|  1|  1|
|  7|  5|  6|  2|
|  7|  3|  5|  3|
|  4|  5|  4|  4|
+---+---+---+---+

我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM