【问题标题】:Getting Number of weeks a month in a pyspark在pyspark中获取每月的周数
【发布时间】:2021-06-07 01:06:46
【问题描述】:

在 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:无法将列转换为布尔值:请使用 '&' 表示 'and'、'|'在构建 DataFrame 布尔表达式时,for 'or', '~' for 'not'。

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql calendar


    【解决方案1】:

    您需要使用 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|
    +----------+---+---------------+
    

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      相关资源
      最近更新 更多