【问题标题】:PySpark replace null in column with value in other columnPySpark 将列中的 null 替换为其他列中的值
【发布时间】:2017-08-16 20:42:06
【问题描述】:

我想用相邻列中的值替换一列中的空值,例如,如果我有

A|B
0,1
2,null
3,null
4,2

我希望它是:

A|B
0,1
2,2
3,3
4,2

试过

df.na.fill(df.A,"B")

但没用,它说 value 应该是 float、int、long、string 或 dict

有什么想法吗?

【问题讨论】:

    标签: python apache-spark pyspark


    【解决方案1】:

    我们可以使用coalesce

    from pyspark.sql.functions import coalesce
        
    df.withColumn("B",coalesce(df.B,df.A)) 
    

    【讨论】:

    • 此解决方案缺少 from pyspark.sql.functions import coalesce
    【解决方案2】:

    另一个答案。

    如果下面的df1 你的数据框

    rd1 = sc.parallelize([(0,1), (2,None), (3,None), (4,2)])
    df1 = rd1.toDF(['A', 'B'])
    
    from pyspark.sql.functions import when
    df1.select('A',
               when( df1.B.isNull(), df1.A).otherwise(df1.B).alias('B')
              )\
       .show()
    

    【讨论】:

      【解决方案3】:
      df.rdd.map(lambda row: row if row[1] else Row(a=row[0],b=row[0])).toDF().show()
      

      【讨论】:

      • 谢谢,最后,我使用了 coallesce : df.withColumn("B",coalesce(df.B,df.A)) 但如果其他人尝试此操作,您的回答会很有帮助。
      【解决方案4】:

      注意:coalesce 不会替换 NaN 值,仅替换 nulls:

      import pyspark.sql.functions as F
      
      >>> cDf = spark.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b"))
      >>> cDf.show()
      +----+----+
      |   a|   b|
      +----+----+
      |null|null|
      |   1|null|
      |null|   2|
      +----+----+
      
      >>> cDf.select(F.coalesce(cDf["a"], cDf["b"])).show()
      +--------------+
      |coalesce(a, b)|
      +--------------+
      |          null|
      |             1|
      |             2|
      +--------------+
      
      

      现在让我们创建一个带有None 条目的pandas.DataFrame,将其转换为spark.DataFrame 并再次使用coalesce

      >>> cDf_from_pd = spark.createDataFrame(pd.DataFrame({'a': [None, 1, None], 'b': [None, None, 2]}))
      >>> cDf_from_pd.show()
      +---+---+
      |  a|  b|
      +---+---+
      |NaN|NaN|
      |1.0|NaN|
      |NaN|2.0|
      +---+---+
      
      >>> cDf_from_pd.select(F.coalesce(cDf_from_pd["a"], cDf_from_pd["b"])).show()
      +--------------+
      |coalesce(a, b)|
      +--------------+
      |           NaN|
      |           1.0|
      |           NaN|
      +--------------+
      
      

      在这种情况下,您需要先在您的DataFrame 上调用replace 以将NaNs 转换为nulls。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-18
        • 2023-02-07
        相关资源
        最近更新 更多