【问题标题】: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?如何创建一个函数来检查 PySpark 数据框的 2 列中的值是否与另一个数据框的相同 2 列中的值匹配?
【发布时间】:2022-01-16 02:15:20
【问题描述】:

您将如何创建一个函数来检查数据框的两个 PySpark 列中的值是否与另一个 Pysark 数据框的相同两列中的值匹配?如果两列中的这些值存在于另一个数据框中,我想创建一个新列来显示验证。数据框没有相同的列,除了要加入的两列。我是 PySpark 的新手。下面的代码显示了一个在匹配一列时识别验证的函数:

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()

上面的函数可以显示 PySpark df 的一列中的值是否存在于同一列的另一个 df 中。我想修改此代码以允许函数将 df1 中的两列中的值与 df2 中的两列中的值匹配,并让用户知道 df1 中的两列中的值是否存在于 df2 中的两列中。例如:

firstname lastname gender
Sam Smith M
Anna Rose F
Robert Williams M
firstname lastname gender salary
Gerogie Smith M 3000
Anna Rose F 4100
Robert Williams M 6200
firstname lastname values_do_notExist_inOtherTable
Sam Smith true
Anna Rose false
Robert Williams false

【问题讨论】:

    标签: python dataframe pyspark


    【解决方案1】:

    您可以在firstnamelastname 上都使用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|
    +---------+--------+------+-------------------------------+
    

    【讨论】:

    • 如何以函数格式完成?我尝试将它放在函数格式中,并且错误指出列不明确。
    • 函数内部或外部的逻辑无关紧要,我可以将示例更新为函数。 df2_nonCorresponding_column 已从函数中删除,因为它不是必需的,并且连接列可用于查找丢失的记录。如果这对您没有帮助,请考虑使用您观察到的错误更新问题。
    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多