英文:
How to access dataframe column in pyspark and do string comparision?
问题
以下是您要求的代码部分的翻译:
我有一个Python函数,根据数据框的列的值返回True/False。
def check_name(df):
  if ((df.name == "ABC")):
      return ((df.Value < 0.80))
    return (df.Value == 0)
然后我将这个函数作为`myFunction`传递给我的查询:
def myQuery(myFunction):
    df.filter(...).groupBy(...).withColumn('Result', when(myFunction(df), 0).otherwise(1))
但它失败了:
无法将列转换为布尔值:请在构建DataFrame布尔表达式时使用'&'表示'and','|'表示'or','~'表示'not'。
我认为问题在于这个`df.name == "ABC"`。
我尝试将其更改为`F.col('name')` == "ABC",但是我得到了相同的错误。
您能告诉我如何解决我的问题吗?
英文:
I have a python function which return True/False depends on value of a data frame column.
def check_name(df):
  if ((df.name == "ABC")):
      return ((df.Value < 0.80))
    return (df.Value == 0)
And I pass this function into my query as myFunction:
def myQuery(myFunction):
    df.filter(...).groupBy(...).withColumn('Result', when(myFunction(df), 0).otherwise(1))
But it fails
Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.
I think the problem is this df.name == "ABC"
I have tried changing to F.col('name') == "ABC", but I get the same error.
Can you please tell me how to fix my issue?
答案1
得分: 0
if-else 代码应该变成 Spark 中的指令 (when.otherwise)。
def check_name(df):
    return F.when(df.id == "ABC", df.score1 < 0.80).otherwise(df.score1 == 0)
然后,如果 myFunction 必须返回布尔值,并且您要反转布尔值(true = 0, false = 1),您可以简化 myQuery 如下:
def myQuery(myFunction):
    return (df.filter(...)
            .groupBy(...)
            .withColumn('Result', (~myFunction(df).cast('int')))
英文:
if-else code should be instructions (when.otherwise) in spark.
def check_name(df):
    return F.when(df.id == "ABC", df.score1 < 0.80).otherwise(df.score1 == 0)
and then if myFunction must return boolean and you are inverting the boolean value (true = 0, false = 1), you can simplify the myQuery to be
def myQuery(myFunction):
    return (df.filter(...)
            .groupBy(...)
            .withColumn('Result', (~myFunction(df).cast('int')))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论