且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pyspark 滞后函数(基于列)

更新时间:2023-02-02 22:54:20

lag 函数的参数 count 采用整数而不是列对象:

The argument count of the lag function takes an integer not a column object :

psf.lag(col, count=1, default=None)

因此它不能是动态"值.相反,您可以在列中建立滞后,然后将表与自身连接.

Therefore it cannot be a "dynamic" value. Instead you can build your lag in a column and then join the table with itself.

首先让我们创建我们的数据框:

First let's create our dataframe:

df = spark.createDataFrame(
    sc.parallelize(
        [[1, "2011-01-01"], [1, "2012-01-01"], [2, "2013-01-01"], [1, "2014-01-01"]]
    ), 
    ["int", "date"]
)

我们要枚举行:

from pyspark.sql import Window
import pyspark.sql.functions as psf
df = df.withColumn(
    "id", 
    psf.monotonically_increasing_id()
)
w = Window.orderBy("id")
df = df.withColumn("rn", psf.row_number().over(w))
    +---+----------+-----------+---+
    |int|      date|         id| rn|
    +---+----------+-----------+---+
    |  1|2011-01-01|17179869184|  1|
    |  1|2012-01-01|42949672960|  2|
    |  2|2013-01-01|68719476736|  3|
    |  1|2014-01-01|94489280512|  4|
    +---+----------+-----------+---+

现在建立滞后:

df1 = df.select(
    "int", 
    df.date.alias("date1"), 
    (df.rn - df.int).alias("rn")
)
df2 = df.select(
    df.date.alias("date2"), 
    'rn'
)

最后我们可以加入它们并计算日期差异:

Finally we can join them and compute the date difference:

df1.join(df2, "rn", "inner").withColumn(
    "date_diff", 
    psf.datediff("date1", "date2")
).drop("rn")

    +---+----------+----------+---------+
    |int|     date1|     date2|date_diff|
    +---+----------+----------+---------+
    |  1|2012-01-01|2011-01-01|      365|
    |  2|2013-01-01|2011-01-01|      731|
    |  1|2014-01-01|2013-01-01|      365|
    +---+----------+----------+---------+