注意:這是針對 Spark 版本 2.1.1.2.6.1.0-129
我有一個火花資料框(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
uj5u.com熱心網友回復:
顯然在 Spark 2.1.1 中,df.na.replace 不支持 None. None選項僅自 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|
# ---- ---
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334977.html
標籤:Python 数据框 python-2.7 阿帕奇火花 火花
