PySpark:fillna功能即使在铸造类型之后也不工作

PySpark:fillna功能即使在铸造类型之后也不工作,pyspark,fillna,Pyspark,Fillna,我有一个包含两列的数据框,如下所示: +----+-----+ |type|class| +----+-----+ | | 0| | | 0| | | 0| | | 0| | | 0| +----+-----+ only showing top 5 rows df = df.fillna({'type': 'Empty'}) 我试图用一些任意字符串填充空值,因此我执行了以下操作: +----+-----+ |type|class|

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

+----+-----+
|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
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
不是我要找的吗?

fillna
用于替换空值,并且您的类型列中有
'
(空字符串);要替换常规值,可以使用
na.replace
方法:

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

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

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

fillna
用于替换空值,并且您的类型列中有
'
(空字符串),这就是它不起作用的原因。@Psidom那么我将对空字符串使用什么呢?是否有可以处理空字符串的内置函数?为此,可以使用
na.replace
方法。回答如下。
fillna
用于替换空值,并且您的类型列中有
'
(空字符串),这就是它不起作用的原因。@Psidom那么我将对空字符串使用什么?是否有可以处理空字符串的内置函数?为此,可以使用
na.replace
方法。回答如下。非常感谢!这解决了我今天遇到的问题。我想知道是否有任何方法可以同时替换多列中的空字符串谢谢!这解决了我今天遇到的问题。我想知道是否有任何方法可以同时替换多列中的空字符串