Pyspark 将 NaN 替换为 NULL
Pyspark replace NaN with NULL
我使用 Spark 执行加载到 Redshift 中的数据转换。 Redshift 不支持 NaN 值,因此我需要将所有出现的 NaN 替换为 NULL。
我试过这样的事情:
some_table = sql('SELECT * FROM some_table')
some_table = some_table.na.fill(None)
但是我得到了以下错误:
ValueError: value should be a float, int, long, string, bool or dict
所以好像na.fill()
不支持None。我特别需要替换为 NULL
,而不是其他值,例如 0
.
谷歌搜索了一下,我终于找到了答案。
df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b"))
df.show()
+----+---+
| a| b|
+----+---+
| 1|NaN|
|null|1.0|
+----+---+
import pyspark.sql.functions as F
columns = df.columns
for column in columns:
df = df.withColumn(column,F.when(F.isnan(F.col(column)),None).otherwise(F.col(column)))
sqlContext.registerDataFrameAsTable(df, "df2")
sql('select * from df2').show()
+----+----+
| a| b|
+----+----+
| 1|null|
|null| 1.0|
+----+----+
它没有使用na.fill()
,但它实现了相同的结果,所以我很高兴。
df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b"))
df.show()
+----+---+
| a| b|
+----+---+
| 1|NaN|
|null|1.0|
+----+---+
df = df.replace(float('nan'), None)
df.show()
+----+----+
| a| b|
+----+----+
| 1|null|
|null| 1.0|
+----+----+
您可以使用 .replace
函数在一行代码中更改为 null
值。
我使用 Spark 执行加载到 Redshift 中的数据转换。 Redshift 不支持 NaN 值,因此我需要将所有出现的 NaN 替换为 NULL。
我试过这样的事情:
some_table = sql('SELECT * FROM some_table')
some_table = some_table.na.fill(None)
但是我得到了以下错误:
ValueError: value should be a float, int, long, string, bool or dict
所以好像na.fill()
不支持None。我特别需要替换为 NULL
,而不是其他值,例如 0
.
谷歌搜索了一下,我终于找到了答案。
df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b"))
df.show()
+----+---+
| a| b|
+----+---+
| 1|NaN|
|null|1.0|
+----+---+
import pyspark.sql.functions as F
columns = df.columns
for column in columns:
df = df.withColumn(column,F.when(F.isnan(F.col(column)),None).otherwise(F.col(column)))
sqlContext.registerDataFrameAsTable(df, "df2")
sql('select * from df2').show()
+----+----+
| a| b|
+----+----+
| 1|null|
|null| 1.0|
+----+----+
它没有使用na.fill()
,但它实现了相同的结果,所以我很高兴。
df = spark.createDataFrame([(1, float('nan')), (None, 1.0)], ("a", "b"))
df.show()
+----+---+
| a| b|
+----+---+
| 1|NaN|
|null|1.0|
+----+---+
df = df.replace(float('nan'), None)
df.show()
+----+----+
| a| b|
+----+----+
| 1|null|
|null| 1.0|
+----+----+
您可以使用 .replace
函数在一行代码中更改为 null
值。