首页 文章

PySpark:fillna函数即使在转换类型后也无法正常工作

提问于
浏览
-1

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

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

我试图用一些任意字符串填充空值,所以我做了以下事情:

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

这再次向我展示了相同的结果:

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

所以我在周围搜索并发现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 回答

  • 2

    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 方法,它是 na.replace 的别名:

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

相关问题