0

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

+----+-----+
|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

所以我四处搜索,发现这个关于 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我要找的吗?

4

1 回答 1

3

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|
+------------+-----+
于 2018-10-17T20:34:53.443 回答