java - 比较 Java Spark Dataframe 中的日期
问题描述
我有以下 Spark 数据框/数据集。Column_2 具有字符串格式的日期。
Column_1 Column_2
A 2020-08-05
B 2020-08-01
B 2020-09-20
B 2020-12-31
C 2020-05-10
我预期的输出数据框应该在 Column_1 中每个值只有一行,如果 column_2 中有多个日期用于 column_1 中的相同键,则应该选择下一个可用日期。如果只有一行,则应保留日期
预期输出:
Column_1 Column_2
A 2020-08-05
B 2020-09-20
C 2020-05-10
有没有办法实现这个 Java 火花?可能不使用UDF?
解决方案
也许这有帮助-
dataset.show(false);
dataset.printSchema();
/**
*+--------+----------+
* |Column_1|Column_2 |
* +--------+----------+
* |A |2020-08-05|
* |D |2020-08-01|
* |D |2020-08-02|
* |B |2020-08-01|
* |B |2020-09-20|
* |B |2020-12-31|
* |C |2020-05-10|
* +--------+----------+
*
* root
* |-- Column_1: string (nullable = true)
* |-- Column_2: string (nullable = true)
*/
dataset.withColumn("Column_2", to_date(col("Column_2")))
.withColumn("count", count("Column_2").over(Window.partitionBy("Column_1")))
.withColumn("positive", when(col("count").gt(1),
when(col("Column_2").gt(current_date()), col("Column_2"))
).otherwise(col("Column_2")))
.withColumn("negative", when(col("count").gt(1),
when(col("Column_2").lt(current_date()), col("Column_2"))
).otherwise(col("Column_2")))
.groupBy("Column_1")
.agg(min("positive").as("positive"), max("negative").as("negative"))
.selectExpr("Column_1", "coalesce(positive, negative) as Column_2")
.show(false);
/**
* +--------+----------+
* |Column_1|Column_2 |
* +--------+----------+
* |A |2020-08-05|
* |D |2020-08-02|
* |B |2020-09-20|
* |C |2020-05-10|
* +--------+----------+
*/
推荐阅读
- jsf - 添加 Primefaces 扩展的 CKEditor 时出错
- google-cloud-platform - 从 gcloud 命令行列出市场中的 gcp 映像
- c# - c#/WinForms - 从资源中获取文件并将其放在 C: 驱动器上的目录中
- c# - RequestURI 在 API 链接 asp.net 中去除“点”
- scikit-learn - 导入 eli5、Python 3.7、sklearn 版本 0.19.2 时出错
- c++ - Matlab与QT图形集成
- hl7-fhir - 无法理解 Schema/Schematron Validator 的重要性
- postgresql - 在postgresql中加入主键缓慢
- vb.net - 用于 OracleInProcServer.OraDynaset 的 vb6 到 vb.net
- java - 使用 privateKey 签署消息(椭圆 p256)