【问题标题】:pyspark join 2 tables and change a column value only if 2nd table has an entrypyspark 仅在第二个表有条目时才加入 2 个表并更改列值
【发布时间】:2023-03-19 22:27:01
【问题描述】:

我有 table_1 和 table_2 如下:

table_1

ID  name   qty
1   ball   34
2   pen    45
5   ham    22
4   van    1
9   phone  200

table_2 的数量已更改

ID  name   changed_qty
1   ball   70
5   ham    400
9   phone  89

我想根据列 ['ID', 'name'] 连接 table_1 和 table_2,这样如果第二个表中没有 ID 和名称,那么我想保留 table_1 行本身。如果 table_2 中有 ID 和 name,那么我想从第二个表中提取 qty 列。

预期结果:

ID  name   qty
1   ball   70
2   pen    45
5   ham    400
4   van    1
9   phone  89

正常的左连接不会为我提供预期的结果。

df_final = df_table_1.join(df_table_2, ['ID', 'name'], how="left")

【问题讨论】:

    标签: apache-spark join pyspark apache-spark-sql


    【解决方案1】:

    合并两列,即将changed_qty中的空值替换为qty:

    import pyspark.sql.functions as F
    
    final = table1.join(table2, ['ID', 'name'], 'left').select('ID', 'name', F.coalesce('changed_qty', 'qty').alias('qty'))
    
    final.show()
    +---+-----+---+
    | ID| name|qty|
    +---+-----+---+
    |  1| ball| 70|
    |  2|  pen| 45|
    |  5|  ham|400|
    |  4|  van|  1|
    |  9|phone| 89|
    +---+-----+---+
    

    【讨论】:

      猜你喜欢
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2022-01-02
      相关资源
      最近更新 更多