如何在 PySpark Dataframe 列中将日期转换为月份的第一天? [英] How to convert date to the first day of month in a PySpark Dataframe column?

查看:30
本文介绍了如何在 PySpark Dataframe 列中将日期转换为月份的第一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据帧:

+----------+
|      date|
+----------+
|2017-01-25|
|2017-01-21|
|2017-01-12|
+----------+

这是上面创建DataFrame的代码:

Here is the code the create above DataFrame:

import pyspark.sql.functions as f
rdd = sc.parallelize([("2017/11/25",), ("2017/12/21",), ("2017/09/12",)])
df = sqlContext.createDataFrame(rdd, ["date"]).withColumn("date", f.to_date(f.col("date"), "yyyy/MM/dd"))
df.show()

我想要一个新列,每一行都有一个月的第一个日期,只需将所有日期中的日期替换为01"

I want a new column with the first date of month for each row, just replace the day to "01" in all the dates

+----------++----------+
|      date| first_date|
+----------++----------+
|2017-11-25| 2017-11-01|
|2017-12-21| 2017-12-01|
|2017-09-12| 2017-09-01|
+----------+-----------+

PySpark.sql.function 中有 last_day 函数,但是没有 first_day 函数.

There is a last_day function in PySpark.sql.function, however, there is no first_day function.

我尝试使用 date_sub 来执行此操作,但没有奏效:我收到一个列不是 Iterable 错误,因为 date_sub 的第二个参数不能是列并且必须是整数.

I tried using date_sub to do this but did not work: I get a column not Iterable error because the second argument to date_sub cannot be a column and has to be an integer.

f.date_sub(f.col('date'), f.dayofmonth(f.col('date')) - 1 )

推荐答案

你可以使用trunc:

import pyspark.sql.functions as f

df.withColumn("first_date", f.trunc("date", "month")).show()

+----------+----------+
|      date|first_date|
+----------+----------+
|2017-11-25|2017-11-01|
|2017-12-21|2017-12-01|
|2017-09-12|2017-09-01|
+----------+----------+

这篇关于如何在 PySpark Dataframe 列中将日期转换为月份的第一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆