【问题标题】:Filtering records in pyspark dataframe if the struct Array contains a record如果结构数组包含记录,则过滤 pyspark 数据框中的记录
【发布时间】:2021-12-08 17:46:30
【问题描述】:

我的 Pyspark 数据框如下所示:

|-- name: string (nullable = true)
 |-- other_attr: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- key: string (nullable = true)
 |    |    |-- value: string (nullable = true)

我正在寻找在 other_attr 下的结构数组中没有 [Closed, Yes] 的行。 other_attr 是一个结构数组,可以是一个空数组。如何运行此过滤?

【问题讨论】:

    标签: dataframe pyspark filter


    【解决方案1】:

    您可以像这样简单地使用array_contains 来检查结构[Closed, Yes]

    import pyspark.sql.functions as F
    
    df.show()
    # +-----+---------------+
    # | name|     other_attr|
    # +-----+---------------+
    # |test1|[{Closed, Yes}]|
    # |test2| [{Closed, No}]|
    # |test3|             []|
    # +-----+---------------+
    
    (df.where(~F
            .array_contains('other_attr', F.struct(
                F.lit('Closed').alias('key'),
                F.lit('Yes').alias('value'),
            ))
        ).show()
    )
    
    # Output
    # +-----+--------------+
    # | name|    other_attr|
    # +-----+--------------+
    # |test2|[{Closed, No}]|
    # |test3|            []|
    # +-----+--------------+
    

    【讨论】:

    • TypeError: 'Column' object is not callable 我得到这个错误!
    • 你的代码是什么样的?我在作为答案发布之前进行了测试,因此上面的输出。 (另外,IMO,在否决某人花时间回答您的问题之前,您不应该讨论一下错误吗?)
    • 很抱歉投了反对票!我错误地投票并想删除投票,这发生了。请编辑代码,以便我为您投票。
    【解决方案2】:

    您可以使用 to_json 函数和 contains 来根据条件过滤行。

    import pyspark.sql.functions as F
    
    df2 = df.filter(
        ~F.to_json('other_attr').contains(
            F.to_json(
                F.struct(
                    F.lit('Closed').alias('key'),
                    F.lit('Yes').alias('value')
                )
            )
        )
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2013-05-07
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多