[英]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 to create a function that checks if values in 2 columns of a PySpark dataframe matches values in the same 2 columns of another dataframe?
How would you create a function that checks if values in two PySpark columns of a dataframe matches values in the same two columns of another Pysark dataframe? 如果两列中的这些值存在于另一个 dataframe 中,我想创建一个新列来显示验证。 数据框没有相同的列,除了要加入的两列。 我是 PySpark 的新手。 下面的代码显示了一个 function 在匹配一列时识别验证:
def isValue_inTable(df1, df2, column_name,
df2_nonCorresponding_column):
df3 = (df1.join(df2, on=column_name, how='left')
.withColumn('Value_inTable',
F.when(df2[df2_nonCorresponding_column].isNull(),
False).otherwise(True)))
df3.select(column_name, 'Value_inTable').show()
上面的 function 可以显示 PySpark df 的一列中的值是否存在于同一列的另一个 df 中。 我想修改此代码以允许 function 将 df1 中的两列中的值匹配到 df2 中的两列,并让用户知道 df1 中的两列中的值是否存在于 df2 的两列中。 例如:
名 | 姓 | 性别 |
---|---|---|
山姆 | 史密斯 | 米 |
安娜 | 玫瑰 | F |
罗伯特 | 威廉姆斯 | 米 |
名 | 姓 | 性别 | 薪水 |
---|---|---|---|
杰罗吉 | 史密斯 | 米 | 3000 |
安娜 | 玫瑰 | F | 4100 |
罗伯特 | 威廉姆斯 | 米 | 6200 |
名 | 姓 | values_do_notExist_inOtherTable |
---|---|---|
山姆 | 史密斯 | 真的 |
安娜 | 玫瑰 | 错误的 |
罗伯特 | 威廉姆斯 | 错误的 |
您可以在firstname
和lastname
上left join
,然后根据null
条件构造values_do_notExist_inOtherTable
。
from pyspark.sql import functions as F
df1_data = [("Sam", "Smith", "M", ), ("Anna", "Rose", "F", ), ("Robert", "Williams", "M", ), ]
df2_data = [("Gerogie", "Smith", "M", 3000, ), ("Anna", "Rose", "F", 4100, ), ("Robert", "Williams", "M", 6200, )]
df1 = spark.createDataFrame(df1_data, ("firstname", "lastname", "gender", ))
df2 = spark.createDataFrame(df2_data, ("firstname", "lastname", "gender", "salary", ))
def isValue_inTable(df1, df2, join_columns):
return (df1.join(df2, on=join_columns, how="left")
.withColumn("values_do_notExist_inOtherTable", F.when(df2[join_columns[0]].isNull() |
df2[join_columns[1]].isNull(), True).otherwise(False))
.select(df1["firstname"], df1["lastname"], df1["gender"], "values_do_notExist_inOtherTable"))
isValue_inTable(df1, df2, ["firstname", "lastname"]).show()
|firstname|lastname|gender|values_do_notExist_inOtherTable|
+---------+--------+------+-------------------------------+
| Anna| Rose| F| false|
| Robert|Williams| M| false|
| Sam| Smith| M| true|
+---------+--------+------+-------------------------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.