【发布时间】:2021-07-24 13:07:11
【问题描述】:
我正在尝试将某个日期减去几个月。我有以下名为 df1 的 DF,其中 MonthSub 始终为正数,因此我必须将其转换为负数以减去日期:
+-------------+----------+
| Date | MonthSub |
+-------------+----------+
| 31/11/2020 | 12 |
| 25/07/2020 | 5 |
| 11/01/2020 | 1 |
+-------------+----------+
我希望得到以下结果:
+-------------+----------+-------------+
| Date | MonthSub | Result |
+-------------+----------+-------------+
| 31/11/2020 | 12 | 31/11/2019 |
| 25/07/2020 | 5 | 25/02/2020 |
| 11/01/2020 | 1 | 11/12/2019 |
+-------------+----------+-------------+
DF1 的架构:
root
|-- Date: string (nullable = true)
|-- MonthSub: string (nullable = true)
我在做什么:
df1 = df1.withColumn("MonthSub", col("MonthSub").cast(IntegerType))
val dfMonth = df1.withColumn("Result", add_months(to_date(col("Date"), "dd-MM-yyyy"), col("MonthSub")))
但我不断得到空值。 还有其他选择吗?还是我做错了什么?
【问题讨论】:
-
您可以在帖子中添加数据框的架构吗? (printSchema() 函数)
-
@David 完成,我尝试将 MonthSub 转换为 int 和 Date 到日期但不起作用,使用演员更新代码。
标签: scala apache-spark date