【问题标题】:From many pyspark columns (with certain condition) to one column with all the conditions combined. PYSPARK从许多 pyspark 列(具有特定条件)到结合所有条件的一列。火花
【发布时间】:2019-06-12 19:54:56
【问题描述】:

我有一个 Python 列表,其中包含一些包含特定条件的 PySpark 列。我只想有一个列来总结我在列列表中的所有条件。

我尝试使用 sum() 操作来合并所有列,但它不起作用(显然)。另外,我一直在检查文档https://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html 但似乎没有什么对我有用。
我正在做这样的事情:

my_condition_list = [col(c).isNotNull() for c in some_of_my_sdf_columns]

返回一个不同 Pyspark 列的列表,我只想要一个包含所有条件并结合 |运算符,因此我可以在 .filter() 或 .when() 子句中使用它。

谢谢你

【问题讨论】:

    标签: pyspark pyspark-sql


    【解决方案1】:

    PySpark 不接受关于where/filter 条件的列表。它接受string 或condition。

    你尝试过的方式行不通,你需要调整某些东西才能工作。以下是两种方法 -

    data = [(("ID1", 3, None)), (("ID2", 4, 12)), (("ID3", None, 3))]
    df = spark.createDataFrame(data, ["ID", "colA", "colB"])
    df.show()
    
    from pyspark.sql import functions as F 
    

    方式 - 1

    #below change df_name if you have any other name
    df_name = "df"
    my_condition_list = ["%s['%s'].isNotNull()"%(df_name, c) for c in df.columns]
    
    print (my_condition_list[0])
    "df['ID'].isNotNull()"
    
    print (" & ".join(my_condition_list))
    "df['ID'].isNotNull() & df['colA'].isNotNull() & df['colB'].isNotNull()"
    
    print (eval(" & ".join(my_condition_list)))
    Column<b'(((ID IS NOT NULL) AND (colA IS NOT NULL)) AND (colB IS NOT NULL))'>
    
    df.filter(eval(" & ".join(my_condition_list))).show()
    +---+----+----+
    | ID|colA|colB|
    +---+----+----+
    |ID2|   4|  12|
    +---+----+----+
    
    df.filter(eval(" | ".join(my_condition_list))).show()
    +---+----+----+
    | ID|colA|colB|
    +---+----+----+
    |ID1|   3|null|
    |ID2|   4|  12|
    |ID3|null|   3|
    +---+----+----+
    

    方式 - 2

    my_condition_list = ["%s is not null"%c for c in df.columns]
    print (my_condition_list[0])
    'ID is not null'
    
    print (" and ".join(my_condition_list))
    'ID is not null and colA is not null and colB is not null'
    
    df.filter(" and ".join(my_condition_list)).show()
    +---+----+----+
    | ID|colA|colB|
    +---+----+----+
    |ID2|   4|  12|
    +---+----+----+
    
    df.filter(" or ".join(my_condition_list)).show()
    +---+----+----+
    | ID|colA|colB|
    +---+----+----+
    |ID1|   3|null|
    |ID2|   4|  12|
    |ID3|null|   3|
    +---+----+----+
    

    首选方式是方式 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 2019-05-24
      相关资源
      最近更新 更多