【问题标题】:pyspark case statement over window function窗口函数上的 pyspark case 语句
【发布时间】:2021-07-02 04:27:30
【问题描述】:

我有一个数据框,我需要在其中检查以下三列以过滤正确的行。

给定数据框输入:

customer_number acct_registration_ts          last_login_ts acct_create_ts
28017150        null                           null         2018-02-13T00:43:26.747+0000
28017150        null                           null         2014-09-11T15:58:29.593+0000
28017150        2014-05-14T23:11:40.167+0000   null         2014-05-12T00:00:00.000+0000

预期的数据框输出:

customer_number acct_registration_ts          last_login_ts acct_create_ts
28017150        2014-05-14T23:11:40.167+0000   null         2014-05-12T00:00:00.000+0000

过滤条件:

  1. 如果 acct_registration_ts 不为 NULL,则获取 acct_registration_ts 行的最大值。
  2. 如果 acct_registration_ts 为 NULL,则检查 last_login_ts,如果 last_login_ts 不为 NULL,则获取 last_login_ts 行的最大值。
  3. 如果 acct_registration_ts 和 last_login_ts 都为 NULL,则获取 acct_create_ts 行的最大值。

这里我需要按 customer_number 列分组,然后应用上述 3 个过滤逻辑。我尝试使用 pyspark 窗口功能,但没有得到预期的输出。任何帮助将不胜感激。

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql window-functions


    【解决方案1】:

    您可以在所有三列中使用一个窗口:

    from pyspark.sql import functions as F, Window
    
    w = Window.partitionBy('customer_number').orderBy(*[F.desc_nulls_last(c) for c in df.columns[1:]])
    
    df2 = df.withColumn('rn', F.dense_rank().over(w)).filter('rn = 1')
    
    df2.show(truncate=False)
    +---------------+----------------------------+-------------+----------------------------+---+
    |customer_number|acct_registration_ts        |last_login_ts|acct_create_ts              |rn |
    +---------------+----------------------------+-------------+----------------------------+---+
    |28017150       |2014-05-14T23:11:40.167+0000|null         |2014-05-12T00:00:00.000+0000|1  |
    +---------------+----------------------------+-------------+----------------------------+---+
    

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 2022-08-18
      • 2014-08-24
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多