【问题标题】:fill null values by joining dataframe with different number of rows and on multiple column通过加入具有不同行数和多列的数据框来填充空值
【发布时间】:2021-05-27 14:36:44
【问题描述】:

我尝试过搜索,但虽然我遇到了类似的情况,但我没有找到我要找的东西。

我有以下两个数据框:

+---------------------------+
|   ID|       Value|   type |
+---------------------------+
|  user0|     100  |   Car  |
|  user1|     102  |   Car  |
|  user2|     109  |   Dog  |
|  user3|     103  |   NA   |
|  user4|     110  |   Dog  |
|  user5|     null |   null |
|  user6|     null |   null |
|  user7|     null |   null |
+---------------------------+

+---------------------------+
|   ID2|     Value2|  type2|
+---------------------------+
|  user5|     115  |  Cell  |
|  user6|     103  |  Cell  |
|  user7|     100  |  Fridge|
+---------------------------+

我想加入这两个,结果如下:

+---------------------------+
|   ID|       Value|   type |
+---------------------------+
|  user0|     100  |   Car  |
|  user1|     102  |   Car  |
|  user2|     109  |   Dog  |
|  user3|     103  |   NA   |
|  user4|     110  |   Dog  |
|  user5|     115  |   Cell |
|  user6|     103  |   Cell |
|  user7|     100  | Fridge |
+---------------------------+  

我尝试了以下方法,但没有返回预期的结果:

df_joined= df1.join(df2,(df1.id==df2.id2) &
                      (df1.value==df2.value2) &
                     (df1.type==df2.type2),
                      "left").drop('id2','value2','type2')  

我只从第一个 df 获取值,可能 left 不是正确的连接类型,但我不明白应该使用什么。

【问题讨论】:

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


    【解决方案1】:

    您只需要使用 ID 加入,而不是其他列,因为其他列不一样。要合并其他列,请使用coalesce,它给出第一个非空值。

    import pyspark.sql.functions as F
    
    df_joined = df1.join(df2, df1.ID == df2.ID2, 'left').select(
        'ID',
        F.coalesce(df1.Value, df2.Value2).alias('Value'),
        F.coalesce(df1.type, df2.type2).alias('type')
    )
    
    df_joined.show()
    +-----+-----+------+
    |   ID|Value|  type|
    +-----+-----+------+
    |user0|  100|   Car|
    |user1|  102|   Car|
    |user2|  109|   Dog|
    |user3|  103|    NA|
    |user4|  110|   Dog|
    |user5|  115|  Cell|
    |user6|  103|  Cell|
    |user7|  100|Fridge|
    +-----+-----+------+
    

    【讨论】:

      【解决方案2】:

      你也可以使用 union 然后得到最大值:

      from pyspark.sql import functions as F
      
      result = df1.union(df2).groupBy("ID").agg(
          F.max("value").alias("value"),
          F.max("type").alias("type")
      )
      
      result.show()
      #+-----+-----+------+
      #|   ID|value|  type|
      #+-----+-----+------+
      #|user0|  100|   Car|
      #|user1|  102|   Car|
      #|user2|  109|   Dog|
      #|user3|  103|    NA|
      #|user4|  110|   Dog|
      #|user5|  115|  Cell|
      #|user6|  103|  Cell|
      #|user7|  100|Fridge|
      #+-----+-----+------+
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-06
        • 1970-01-01
        • 2015-11-09
        • 1970-01-01
        • 2016-10-11
        • 2013-04-28
        • 1970-01-01
        • 2021-05-14
        相关资源
        最近更新 更多