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

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

问题描述

我有以下DataFrame:

I have the following 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:

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天全站免登陆