python - 如何在 PySpark 中从年、月和日创建日期?

标签 python apache-spark pyspark apache-spark-sql pyspark-dataframes

我有关于年、月和日的三列。如何使用这些在 PySpark 中创建日期?

最佳答案

您可以使用 concat_ws() 将列与 - 连接起来并转换为日期。

#sampledata
df.show()

#+----+-----+---+
#|year|month|day|
#+----+-----+---+
#|2020|   12| 12|
#+----+-----+---+
from pyspark.sql.functions import *

df.withColumn("date",concat_ws("-",col("year"),col("month"),col("day")).cast("date")).show()
+----+-----+---+----------+
|year|month|day|      date|
+----+-----+---+----------+
|2020|   12| 12|2020-12-12|
+----+-----+---+----------+

#dynamic way
cols=["year","month","day"]
df.withColumn("date",concat_ws("-",*cols).cast("date")).show()
#+----+-----+---+----------+
#|year|month|day|      date|
#+----+-----+---+----------+
#|2020|   12| 12|2020-12-12|
#+----+-----+---+----------+

#using date_format,to_timestamp,from_unixtime(unix_timestamp) functions

df.withColumn("date",date_format(concat_ws("-",*cols),"yyyy-MM-dd").cast("date")).show()
df.withColumn("date",to_timestamp(concat_ws("-",*cols),"yyyy-MM-dd").cast("date")).show()
df.withColumn("date",to_date(concat_ws("-",*cols),"yyyy-MM-dd")).show()
df.withColumn("date",from_unixtime(unix_timestamp(concat_ws("-",*cols),"yyyy-MM-dd"),"yyyy-MM-dd").cast("date")).show()
#+----+-----+---+----------+
#|year|month|day|      date|
#+----+-----+---+----------+
#|2020|   12| 12|2020-12-12|
#+----+-----+---+----------+

关于python - 如何在 PySpark 中从年、月和日创建日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60954146/

相关文章:

python - PySpark 中的聚合

python - Pyspark 和 Pandas 是否经过认证可以一起工作?

python - JSON 对象必须是 str,而不是 'bytes'

hadoop - 无法在 yarn 模式下启动 Spark Shell

hadoop - 用于处理保存在 HDFS 中的小型二进制文件的 Spark 架构

python - 来自执行程序的 PySpark 日志记录

python - 不要在 Spark (Python) 中写入 None 或空行

python - 如何在 pandas 的 groupby 之后乘以一列的行?

python - 如何从 Google Plus 企业列表中提取类别?

python - 对 .xml 文件中 <P> 内的句子进行编号?