【问题标题】:Using variable in expression with Nullif fails在带有 Nullif 的表达式中使用变量失败
【发布时间】:2021-06-21 10:19:22
【问题描述】:

我正在使用下面的代码将空字符串转换为 Null。 我没有收到错误消息,但它仍然是一个空字符串。
我怀疑 expr 中变量 col_name 的使用不正确

for col_name in ['col1', 'col2']:
    df_new = df \
        .withColumn(col_name, F.expr(f"nullif('{col_name}', '')"))

【问题讨论】:

  • f"nullif({col_name}, '')"
  • 我收到一个错误col should be Column .withColumn(col_name, f"nullif({col_name}, '')")
  • 请显示完整的代码和错误
  • 哦,我的意思是F.expr(f"nullif({col_name}, '')")
  • 但不会使用您的代码更新数据框,请参阅下面的答案

标签: variables pyspark expr nullif


【解决方案1】:

你真正想做的是这个。请注意,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}, '')"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多