PySpark replace() 函数不会用 NULL 值替换整数
PySpark replace() function does not replace integer with NULL value
注意:这是针对 Spark 版本 2.1.1.2.6.1.0-129
我有一个 spark 数据框 (Python)。我想用 NULL 值替换整个数据帧中 0 的所有实例(不指定特定的列名)。
下面是我写的代码:
my_df = my_df.na.replace(0, None)
以下是我收到的错误:
File "<stdin>", line 1, in <module>
File "/usr/hdp/current/spark2-client/python/pyspark/sql/dataframe.py", line 1634, in replace
return self.df.replace(to_replace, value, subset)
File "/usr/hdp/current/spark2-client/python/pyspark/sql/dataframe.py", line 1323, in replace
raise ValueError("value should be a float, int, long, string, list, or tuple")
ValueError: value should be a float, int, long, string, list, or tuple
显然在 Spark 2.1.1 中,df.na.replace
does not support None
. None
option is only available since 2.3.0,这不适用于您的情况。
要动态替换值(即无需手动输入列名),您可以使用 df.columns
或 df.dtypes
。后者也会为您提供比较数据类型的选项。
from pyspark.sql import functions as F
for c in df.dtypes:
if c[1] == 'bigint':
df = df.withColumn(c[0], F.when(F.col(c[0]) == 0, F.lit(None)).otherwise(F.col(c[0])))
# Input
# +---+---+
# | id|val|
# +---+---+
# | 0| a|
# | 1| b|
# | 2| c|
# +---+---+
# Output
# +----+---+
# | id|val|
# +----+---+
# |null| a|
# | 1| b|
# | 2| c|
# +----+---+
注意:这是针对 Spark 版本 2.1.1.2.6.1.0-129
我有一个 spark 数据框 (Python)。我想用 NULL 值替换整个数据帧中 0 的所有实例(不指定特定的列名)。
下面是我写的代码:
my_df = my_df.na.replace(0, None)
以下是我收到的错误:
File "<stdin>", line 1, in <module>
File "/usr/hdp/current/spark2-client/python/pyspark/sql/dataframe.py", line 1634, in replace
return self.df.replace(to_replace, value, subset)
File "/usr/hdp/current/spark2-client/python/pyspark/sql/dataframe.py", line 1323, in replace
raise ValueError("value should be a float, int, long, string, list, or tuple")
ValueError: value should be a float, int, long, string, list, or tuple
显然在 Spark 2.1.1 中,df.na.replace
does not support None
. None
option is only available since 2.3.0,这不适用于您的情况。
要动态替换值(即无需手动输入列名),您可以使用 df.columns
或 df.dtypes
。后者也会为您提供比较数据类型的选项。
from pyspark.sql import functions as F
for c in df.dtypes:
if c[1] == 'bigint':
df = df.withColumn(c[0], F.when(F.col(c[0]) == 0, F.lit(None)).otherwise(F.col(c[0])))
# Input
# +---+---+
# | id|val|
# +---+---+
# | 0| a|
# | 1| b|
# | 2| c|
# +---+---+
# Output
# +----+---+
# | id|val|
# +----+---+
# |null| a|
# | 1| b|
# | 2| c|
# +----+---+