如何在pyspark中访问dataframe列并进行字符串比较?

2ic8powd  于 2023-06-21  发布在  Spark
关注(0)|答案(1)|浏览(118)

我有一个python函数,它返回True/False取决于数据框列的值。

  1. def check_name(df):
  2. if ((df.name == "ABC")):
  3. return ((df.Value < 0.80))
  4. return (df.Value == 0)

我将这个函数作为myFunction传递到查询中:

  1. def myQuery(myFunction):
  2. df.filter(...).groupBy(...).withColumn('Result', when(myFunction(df), 0).otherwise(1))

但它失败了

  1. Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.

我觉得问题出在这个df.name == "ABC"
我试着修改为F.col('name') ==“ABC”,但我得到了同样的错误。
你能告诉我如何解决我的问题吗?

jgwigjjp

jgwigjjp1#

if-else代码应该是spark中的指令(when.otherwise)。

  1. def check_name(df):
  2. return F.when(df.id == "ABC", df.score1 < 0.80).otherwise(df.score1 == 0)

然后如果myFunction必须返回boolean,并且您正在反转布尔值(true = 0, false = 1),则可以将myQuery简化为

  1. def myQuery(myFunction):
  2. return (df.filter(...)
  3. .groupBy(...)
  4. .withColumn('Result', (~myFunction(df).cast('int')))

相关问题