简体   繁体   English

Pyspark 将年和周数转换为 week_start 日期和 week_end 日期

[英]Pyspark convert Year and week number to week_start Date & week_end Date

I am trying to convert year & week number to the week start date and week end date using the Pyspark dataframe.我正在尝试使用 Pyspark dataframe 将年和周数转换为周开始日期和周结束日期。

+---------+
|year_week|
+---------+
| 2019-W51|
| 2019-W52|
| 2020-W01|
| 2020-W02|
| 2020-W03|
| 2020-W04|
| 2020-W05|
| 2020-W06|
| 2020-W07|
+---------+

When I try to apply the following code, I am getting the error that column object is not iterable当我尝试应用以下代码时,我收到 object 列不可迭代的错误

df = df.withColumn('week_start_date', df.year_week.apply(lambda x: datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")))

Error错误

TypeError: 'Column' object is not callable

The expected result is:预期结果是:

+---------+----------+----------+
|year_week|week_start|  week_end|
+---------+----------+----------+
| 2019-W51|2019-12-16|2019-12-22|
| 2019-W52|2019-12-23|2019-12-29|
| 2020-W01|2019-12-30|2020-01-05|
| 2020-W02|2020-01-06|2020-01-12|
| 2020-W03|2020-01-13|2020-01-19|
| 2020-W04|2020-01-20|2020-01-26|
| 2020-W05|2020-01-27|2020-02-02|
| 2020-W06|2020-02-03|2020-02-09|
| 2020-W07|2020-02-10|2020-02-16|
+---------+----------+----------+

based on the response of Someshwar, only slight changes had to be made for python from scala.根据 Someshwar 的响应,只需对 python 从 scala 进行轻微更改。

df1 = df.withColumn("week_start", F.to_date(F.concat(F.col("year_week"), F.lit("-1")), "YYYY-'W'ww-u")).withColumn("week_end", F.next_day(F.col("week_start"), "SUN"))

Try this-尝试这个-

 // week starting from monday, concat "-1", for tuesday "-2" etc.
    val p = df2.withColumn("week_start", to_date(concat($"year_week", lit("-1")), "YYYY-'W'ww-u"))
      .withColumn("week_end", next_day($"week_start", "SUN"))
    p.show(false)
    p.printSchema()

    /**
      * +---------+----------+----------+
      * |year_week|week_start|week_end  |
      * +---------+----------+----------+
      * |2019-W51 |2019-12-16|2019-12-22|
      * |2019-W52 |2019-12-23|2019-12-29|
      * |2020-W01 |2019-12-30|2020-01-05|
      * |2020-W02 |2020-01-06|2020-01-12|
      * |2020-W03 |2020-01-13|2020-01-19|
      * |2020-W04 |2020-01-20|2020-01-26|
      * |2020-W05 |2020-01-27|2020-02-02|
      * |2020-W06 |2020-02-03|2020-02-09|
      * |2020-W07 |2020-02-10|2020-02-16|
      * +---------+----------+----------+
      *
      * root
      * |-- year_week: string (nullable = true)
      * |-- week_start: date (nullable = true)
      * |-- week_end: date (nullable = true)
      */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM