代码之家  ›  专栏  ›  技术社区  ›  ahajib Shaun McHugh

PySpark:fillna函数即使在类型转换之后也不起作用

  •  -1
  • ahajib Shaun McHugh  · 技术社区  · 7 年前

    我有一个包含两列的数据帧,如下所示:

    +----+-----+
    |type|class|
    +----+-----+
    |    |    0|
    |    |    0|
    |    |    0|
    |    |    0|
    |    |    0|
    +----+-----+
    only showing top 5 rows
    

    我试图用一些任意字符串填充空值,因此我执行了以下操作:

    df = df.fillna({'type': 'Empty'})
    

    同样的结果:

    +----+-----+
    |类型|等级|
    +----+-----+
    |    |    0|
    |    |    0|
    +----+-----+
    仅显示前5行
    

    this post 在stackoverflow上,不匹配的类型可能会导致此问题,因此我:

    df = df.withColumn("type", df["type"].cast("string"))
    df = df.fillna({'type': 'Empty'})
    

    我必须提到,原始数据帧具有以下模式:

    StructField(type,StringType,true)
    

    我也试过:

    df = df.withColumn("type", when(df["type"] != '', df["type"]).otherwise('Empty'))
    

    效果很好。我是不是漏了什么?是 fillna 不是我要找的?

    1 回复  |  直到 7 年前
        1
  •  3
  •   akuiper    7 年前

    fillna '' (空字符串)在类型列中;替换可以使用的常规值 na.replace 方法:

    df.na.replace('', 'Empty String', 'type').show()
    +------------+-----+
    |        type|class|
    +------------+-----+
    |Empty String|    0|
    |Empty String|    0|
    +------------+-----+
    

    或:

    df.na.replace({'': 'Empty String'}, 'type').show()
    +------------+-----+
    |        type|class|
    +------------+-----+
    |Empty String|    0|
    |Empty String|    0|
    +------------+-----+
    

    或使用 DataFrame.replace 方法的别名 :

    df.replace('', 'Empty String', 'type').show()
    +------------+-----+
    |        type|class|
    +------------+-----+
    |Empty String|    0|
    |Empty String|    0|
    +------------+-----+
    
    推荐文章