在单个“ when”中对阵列的每个元素使用“或”运算符。 pyspark数据框的功能 [英] using OR operator for each element of an array in single "when" function of pyspark dataframe

查看:79
本文介绍了在单个“ when”中对阵列的每个元素使用“或”运算符。 pyspark数据框的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列数组

DiversityTypes = ["ABC","EFG","LMN","XYZ"]

我想处理一个Pyspark数据框,在其中创建一个名为 << c code>的新列Is_Diversified 并使用 OR运算符将的值设置为上面提到的 DiversityTypes 在单个 函数中,如下所示:

I want to work on a Pyspark dataframe where I create a new column named "Is_Diversified" and set its value Yes ,No using OR operater on the values of each element of DiversityTypes above mentioned, in a single when function as below:

    p_df = p_df.withColumn('Is_Diversified', f.when(f.col("ABC") == 'Y'|\
                                                    f.col("EFG") == 'Y'|\
                                                    f.col("LMN") == 'Y'|\
                                                    f.col("XYZ") == 'Y'),lit("Yes")).otherwise(lit("No")))

在我们遍历数组的每个元素并同时对其应用OR运算符的地方

into something this, where we iterate over each element of the array and simultaenously have OR operator applied to it

for diversity in DiversityTypes:
    p_df = p_df.withColumn('Is_Diversified', f.when(diversity) == 'Y'),lit("Yes")).otherwise(lit("No")))

我无法在此处应用逻辑,请帮忙,谢谢:)

I can't apply the logic here, please help, Thank you :)

推荐答案

我会使用 functools.reduce 按位或

import pyspark.sql.functions as f
from functools import reduce
from operator import or_

p_df = p_df.withColumn(
    'Is_Diversified', 
    f.when(
        reduce(
            or_, 
            [f.col(c)=="Y" for c in DiversityTypes]
        ), 
        f.lit("Yes")
    ).otherwise(f.lit("No"))
)

这篇关于在单个“ when”中对阵列的每个元素使用“或”运算符。 pyspark数据框的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆