Apache spark 正在尝试在PySpark DataFrame中创建具有最大时间戳的列

Apache spark 正在尝试在PySpark DataFrame中创建具有最大时间戳的列,apache-spark,pyspark,apache-spark-sql,Apache Spark,Pyspark,Apache Spark Sql,我对PySpark真的很陌生。我要做的就是找到“date”列的最大值,并在dataframe中添加一个新列,该列的所有行(重复)都具有此最大日期,以便: A B C a timestamp1 timestamp3 b timestamp2 --------------------> timestamp3 c timestamp

我对PySpark真的很陌生。我要做的就是找到“date”列的最大值,并在dataframe中添加一个新列,该列的所有行(重复)都具有此最大日期,以便:

A      B                                        C
a  timestamp1                              timestamp3
b  timestamp2    -------------------->     timestamp3
c  timestamp3                              timestamp3
我使用以下代码行:

df.withColumn('dummy_column',f.lit((f.max('date'))).cast('timestamp')).show(9)
但我得到了一个错误:

> AnalysisException: grouping expressions sequence is empty, and
> '`part`' is not an aggregate function. Wrap '(CAST(max(`date`) AS
> TIMESTAMP) AS `new_column`)' in windowing function(s) or wrap '`part`'
> in first() (or first_value) if you don't care which value you get.;;

有人能帮我理解为什么会出现此错误,以及如何解决此错误吗?

您可能正在寻找:

import pyspark.sql.functions as f
from pyspark.sql.window import Window

w = Window.rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)
df.withColumn('dummy_column',f.max('date').over(w).cast('timestamp')).show(9)

max
这样的聚合函数使用窗口或分组操作。它们无法独立工作,因为您没有指定聚合函数操作的行范围。

还有一个替代方法可以获取
max\u timestamp
只是
grpubby()
现有数据帧并使用
max()
为了获得
最大时间戳
,将其放入
变量
中,并根据需要使用

在这里创建Df 输入 输出
嗨,它工作了!但这让我很困惑。您能解释一下“rowsBetween()”使用的函数参数是什么吗?谢谢你的回答!请参阅下面的文档。参数指定max函数操作的行范围,在本例中,它包含当前行之前和之后的所有行,即数据帧中的所有行。
df = spark.createDataFrame([(1,"2020-10-13"),(2,"2020-10-14"),(3,"2020-10-15")],[ "id","ts"])
df.show()
#df_max = df.groupBy("ts").agg(F.max("ts").alias("max_ts"))
df_max_var = df_max.collect()[0]['max_ts']
# Taking into a variable for future use
df = df.withColumn("dummy_col", F.lit(df_max_var))
df.show()
+---+----------+
| id|        ts|
+---+----------+
|  1|2020-10-13|
|  2|2020-10-14|
|  3|2020-10-15|
+---+----------+
+---+----------+----------+
| id|        ts| dummy_col|
+---+----------+----------+
|  1|2020-10-13|2020-10-15|
|  2|2020-10-14|2020-10-15|
|  3|2020-10-15|2020-10-15|
+---+----------+----------+