无法将空值转换为 0
unable to convert null value to 0
我正在使用数据块,但我不明白为什么我无法在看起来像常规整数列的情况下将空值转换为 0。
我试过这两个选项:
@udf(IntegerType())
def null_to_zero(x):
"""
Helper function to transform Null values to zeros
"""
return 0 if x == 'null' else x
及以后:
.withColumn("col_test", null_to_zero(col("col")))
并且所有内容都返回为 null。
而第二个选项根本没有任何影响.na.fill(value=0,subset=["col"])
我在这里缺少什么?这是空值与数据块的特定行为吗?
空值表示为 None
,而不是字符串 null
。对于您的情况,最好改用 coalesce 函数,例如(基于文档的示例):
from pyspark.sql.functions import coalesce, lit
cDf = spark.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b"))
cDf.withColumn("col_test", coalesce(cDf["a"], lit(0.0))).show()
会给你想要的行为:
+----+----+--------+
| a| b|col_test|
+----+----+--------+
|null|null| 0.0|
| 1|null| 1.0|
|null| 2| 0.0|
+----+----+--------+
如果你需要更复杂的逻辑,那么你可以使用when/otherwise,条件为空:
cDf.withColumn("col_test", when(cDf["a"].isNull(), lit(0.0)).otherwise(cDf["a"])).show()
我正在使用数据块,但我不明白为什么我无法在看起来像常规整数列的情况下将空值转换为 0。
我试过这两个选项:
@udf(IntegerType())
def null_to_zero(x):
"""
Helper function to transform Null values to zeros
"""
return 0 if x == 'null' else x
及以后:
.withColumn("col_test", null_to_zero(col("col")))
并且所有内容都返回为 null。
而第二个选项根本没有任何影响.na.fill(value=0,subset=["col"])
我在这里缺少什么?这是空值与数据块的特定行为吗?
空值表示为 None
,而不是字符串 null
。对于您的情况,最好改用 coalesce 函数,例如(基于文档的示例):
from pyspark.sql.functions import coalesce, lit
cDf = spark.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b"))
cDf.withColumn("col_test", coalesce(cDf["a"], lit(0.0))).show()
会给你想要的行为:
+----+----+--------+
| a| b|col_test|
+----+----+--------+
|null|null| 0.0|
| 1|null| 1.0|
|null| 2| 0.0|
+----+----+--------+
如果你需要更复杂的逻辑,那么你可以使用when/otherwise,条件为空:
cDf.withColumn("col_test", when(cDf["a"].isNull(), lit(0.0)).otherwise(cDf["a"])).show()