【问题标题】:window functions( lag, lead) implementation in pyspark?pyspark中的窗口函数(滞后,领先)实现?
【发布时间】:2019-02-21 06:54:41
【问题描述】:

以下是附加的 T-SQL 代码。我尝试使用附加的窗口函数将其转换为 pyspark。

case 
           when eventaction = 'IN' and lead(eventaction,1) over (PARTITION BY barcode order by barcode,eventdate,transactionid) in('IN','OUT') 
                then                   lead(eventaction,1) over (PARTITION BY barcode order by barcode,eventdate,transactionid) 
           else ''
      end as next_action

Pyspark 代码使用窗口函数导致错误

Tgt_df = Tgt_df.withColumn((('Lead', lead('eventaction').over(Window.partitionBy("barcode").orderBy("barcode","transactionid", "eventdate")) == 'IN' )|
                    ('1', lead('eventaction').over(Window.partitionBy("barcode").orderBy("barcode","transactionid", "eventdate")) == 'OUT')
                     , (lead('eventaction').over(Window.partitionBy("barcode").orderBy("barcode","transactionid", "eventdate"))).otherwise('').alias("next_action")))

但它不起作用。怎么办!?

【问题讨论】:

    标签: tsql pyspark window pyspark-sql lead


    【解决方案1】:

    withColumn 方法应该用作df.withColumn('name_of_col', value_of_column),这就是你有错误的原因。

    从您的 T-SQL 请求中,对应的 pyspark 代码应该是:

    import pyspark.sql.functions as F
    from pyspark.sql.window import Window
    
    w = Window.partitionBy("barcode").orderBy("barcode","transactionid", "eventdate")
    
    Tgt_df = Tgt_df.withColumn('next_action',
                               F.when((F.col('event_action')=='IN')&(F.lead('event_action', 1).over(w).isin(['IN', 'OUT'])),
                                      F.lead('event_action', 1).over(w)
                                      ).otherwise('')
                               )
    

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 2018-06-20
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2017-04-30
      相关资源
      最近更新 更多