在 pyspark 中获取每月的周数

Getting Number of weeks a month in a pyspark

在 pyspark 中计算一个月中的周数。

date          id
01-01-2020     1
01-02-2020     2
01-03-2020     3
01-04-2020     4

预期数据帧

date          id   no of weeks
01-01-2020     1     5
01-02-2020     2     5
01-03-2020     3     6
01-04-2020     4     5

我使用了下面的代码

df=df.withColumn("number_of_weeks",F.lit((calendar.monthcalendar(F.year(col('date')),F.month(col('date')))

我收到了

ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.

您需要使用 UDF 才能将 Python 模块与 Spark 列一起使用。要使用 F.yearF.month,您还需要先将日期列转换为 DateType,使用 to_date 和适当的日期格式字符串。

import calendar
import pyspark.sql.functions as F

df2 = df.withColumn(
    "number_of_weeks",
    F.udf(lambda y, m: len(calendar.monthcalendar(y, m))) 
    (
        F.year(F.to_date('date', 'dd-MM-yyyy')),
        F.month(F.to_date('date', 'dd-MM-yyyy'))
    )
)

df2.show()
+----------+---+---------------+
|      date| id|number_of_weeks|
+----------+---+---------------+
|01-01-2020|  1|              5|
|01-02-2020|  2|              5|
|01-03-2020|  3|              6|
|01-04-2020|  4|              5|
+----------+---+---------------+