【问题标题】:Spark: Replace missing values with values from another columnSpark:用另一列中的值替换缺失值
【发布时间】:2017-06-27 19:07:09
【问题描述】:

假设您有一个包含一些空值的 Spark 数据框,并且您希望将一列的值替换为另一列的值(如果存在)。在 Python/Pandas 中,您可以使用 fillna() 函数很好地做到这一点:

df = spark.createDataFrame([('a', 'b', 'c'),(None,'e', 'f'),(None,None,'i')], ['c1','c2','c3'])
DF = df.toPandas()
DF['c1'].fillna(DF['c2']).fillna(DF['c3']) 

如何使用 Pyspark 做到这一点?

【问题讨论】:

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


    【解决方案1】:

    您需要使用 coalesce 功能:

    cDf = spark.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b"))
    cDF.show()
    # +----+----+
    # |   a|   b|
    # +----+----+
    # |null|null|
    # |   1|null|
    # |null|   2|
    # +----+----+
    
    cDf.select(coalesce(cDf["a"], cDf["b"])).show()
    # +--------------+
    # |coalesce(a, b)|
    # +--------------+
    # |          null|
    # |             1|
    # |             2|
    # +--------------+
    
    cDf.select('*', coalesce(cDf["a"], lit(0.0))).show()
    # +----+----+----------------+
    # |   a|   b|coalesce(a, 0.0)|
    # +----+----+----------------+
    # |null|null|             0.0|
    # |   1|null|             1.0|
    # |null|   2|             0.0|
    # +----+----+----------------+
    

    您还可以在多个列上应用coalesce

    cDf.select(coalesce(cDf["a"], cDf["b"], lit(0))).show()
    # ...
    

    这个例子取自pyspark.sql API documentation

    【讨论】:

    • 优秀。值得注意的是,可以传递多列来填充值cDf.select(coalesce(cDf["a"], cDf["b"], lit(0))).show()
    • 只要确保列值为“null”而不是“空”字符串。我遇到了这个问题,我不得不使用 df.withColumn('myCol', when(col('myCol') == '', None).otherwise(col) 明确地将其中一列的“空”值设为“null” ('myCol')))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多