Dan*_*lan 8 python apache-spark pyspark
我正在用 Python 编写 Spark 代码。我有一个col(execution_date)时间戳。我如何将其转换为名为 的列,如果日期是周末,则is_weekend值为工作日?10
pau*_*ult 10
假设您有以下 Spark DataFrame:
df.show()
#+-------------------+
#| execution_date|
#+-------------------+
#|2019-08-01 00:00:00|
#|2019-08-02 00:00:00|
#|2019-08-03 00:00:00|
#|2019-08-04 00:00:00|
#|2019-08-05 00:00:00|
#|2019-08-06 00:00:00|
#|2019-08-07 00:00:00|
#|2019-08-08 00:00:00|
#|2019-08-09 00:00:00|
#|2019-08-10 00:00:00|
#+-------------------+
Run Code Online (Sandbox Code Playgroud)
火花版本 2.3+
您可以使用pyspark.sql.functions.dayofweek,它将返回 1 到 7 之间的数字(星期日 = 1,星期六 = 7)。
from pyspark.sql.functions import dayofweek
df.withColumn("is_weekend", dayofweek("execution_date").isin([1,7]).cast("int")).show()
#+-------------------+----------+
#| execution_date|is_weekend|
#+-------------------+----------+
#|2019-08-01 00:00:00| 0|
#|2019-08-02 00:00:00| 0|
#|2019-08-03 00:00:00| 1|
#|2019-08-04 00:00:00| 1|
#|2019-08-05 00:00:00| 0|
#|2019-08-06 00:00:00| 0|
#|2019-08-07 00:00:00| 0|
#|2019-08-08 00:00:00| 0|
#|2019-08-09 00:00:00| 0|
#|2019-08-10 00:00:00| 1|
#+-------------------+----------+
Run Code Online (Sandbox Code Playgroud)
Spark 版本 1.5+
您可以pyspark.sql.functions.date_format使用format = 'EEE'
from pyspark.sql.functions import date_format
df.withColumn(
"is_weekend",
date_format("execution_date", 'EEE').isin(["Sat", "Sun"]).cast("int")
).show()
#+-------------------+----------+
#| execution_date|is_weekend|
#+-------------------+----------+
#|2019-08-01 00:00:00| 0|
#|2019-08-02 00:00:00| 0|
#|2019-08-03 00:00:00| 1|
#|2019-08-04 00:00:00| 1|
#|2019-08-05 00:00:00| 0|
#|2019-08-06 00:00:00| 0|
#|2019-08-07 00:00:00| 0|
#|2019-08-08 00:00:00| 0|
#|2019-08-09 00:00:00| 0|
#|2019-08-10 00:00:00| 1|
#+-------------------+----------+
Run Code Online (Sandbox Code Playgroud)
为了完整起见,两者的中间结果如下所示:
df.withColumn("dow", dayofweek("execution_date"))\
.withColumn("day", date_format("execution_date", 'EEE'))\
.show()
#+-------------------+---+---+
#| execution_date|dow|day|
#+-------------------+---+---+
#|2019-08-01 00:00:00| 5|Thu|
#|2019-08-02 00:00:00| 6|Fri|
#|2019-08-03 00:00:00| 7|Sat|
#|2019-08-04 00:00:00| 1|Sun|
#|2019-08-05 00:00:00| 2|Mon|
#|2019-08-06 00:00:00| 3|Tue|
#|2019-08-07 00:00:00| 4|Wed|
#|2019-08-08 00:00:00| 5|Thu|
#|2019-08-09 00:00:00| 6|Fri|
#|2019-08-10 00:00:00| 7|Sat|
#+-------------------+---+---+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5557 次 |
| 最近记录: |