在带有 Nullif 的表达式中使用变量失败
Using variable in expression with Nullif fails
我正在使用下面的代码将空字符串转换为 Null。
我没有收到错误,但它仍然是一个空字符串。
我怀疑 expr
col_name
的使用不正确
for col_name in ['col1', 'col2']:
df_new = df \
.withColumn(col_name, F.expr(f"nullif('{col_name}', '')"))
你真正想做的是这个。请注意,for 循环将创建并覆盖 df_new
,因此只会更改最后一列。
from pyspark.sql import functions as f
df_new = df
for col_name in ['col1', 'col2']:
df_new = df_new.withColumn(col_name, f.expr(f"nullif({col_name}, '')"))