在 PySpark 日期列中获取每年的最新日期

Getting latest dates from each year in a PySpark date column

我有一个 table 这样的:

+----------+-------------+
|      date|BALANCE_DRAWN|
+----------+-------------+
|2017-01-10| 2.21496454E7|
|2018-01-01| 4.21496454E7|
|2018-01-04| 1.21496454E7|
|2018-01-07| 4.21496454E7|
|2018-01-10| 5.21496454E7|
|2019-01-01| 1.21496454E7|
|2019-01-04| 2.21496454E7|
|2019-01-07| 3.21496454E7|
|2019-01-10| 1.21496454E7|
|2020-01-01| 5.21496454E7|
|2020-01-04| 4.21496454E7|
|2020-01-07| 6.21496454E7|
|2020-01-10| 3.21496454E7|
|2021-01-01| 2.21496454E7|
|2021-01-04| 1.21496454E7|
|2021-01-07| 2.21496454E7|
|2021-01-10| 3.21496454E7|
|2022-01-01| 4.21496454E7|
|2022-01-04| 5.21496454E7|
|2022-01-07|2.209869511E7|
|2022-01-10|3.209869511E7|
+----------+-------------+

有没有办法过滤这个数据帧,所以我得到这样的东西:

+----------+-------------+
|      date|BALANCE_DRAWN|
+----------+-------------+
|2017-01-10| 2.21496454E7|
|2018-01-10| 5.21496454E7|
|2019-01-10| 1.21496454E7|
|2020-01-10| 3.21496454E7|
|2021-01-10| 3.21496454E7|
|2022-01-10|3.209869511E7|
+----------+-------------+

即获取每年的最新日期和相应的 BALANCE_DRAWN 行。

我成功拿到了,但是只有1个案例,代码如下:

df = df.groupby([f.year("date")]).agg(f.last("BALANCE_DRAWN"))

但输出仅为年份:

+----------+-------------+
|      date|BALANCE_DRAWN|
+----------+-------------+
|2017      | 2.21496454E7|
|2018      | 5.21496454E7|
|2019      | 1.21496454E7|
|2020      | 3.21496454E7|
|2021      | 3.21496454E7|
|2022      |3.209869511E7|
+----------+-------------+

结果不错,但我需要让它更灵活。 (不只是年份)

更新: 也许 max() 可以以某种方式使用。 (试了一下,会更新的)

更新 2: 已接受的答案做到了!

df = df.withColumn('year', year(df['date']))
       .groupBy(df['year'])
       .agg(max(df['date']), first(df['BALANCE_DRAWN']))