Python PySpark:从星期一开始到星期天结束,按周计算行数

2024-04-25 21:58:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下列的数据框:

ID  Scheduled Date
241 10/9/2018
423 9/25/2018
126 9/30/2018
123 8/13/2018
132 8/16/2018
143 10/6/2018

我想按周计算身份证的总数。具体来说,我希望这一周总是从周一开始,一直到周日结束。在

我已经在Jupyter笔记本上实现了这一点:

^{2}$

但是我不知道如何用pythonpyspark语法编写上面的代码。我希望结果输出如下所示:

Scheduled Date  Total Count
8/13/2018       2
9/24/2018       2
10/1/2018       1
10/8/2018       1

请注意,计划日期始终是星期一(表示周初),总计数从该周的星期一到星期日。在


Tags: 数据代码iddatecount语法笔记本jupyter
1条回答
网友
1楼 · 发布于 2024-04-25 21:58:21

感谢Get Last Monday in Spark定义了函数前一天

首先导入

from pyspark.sql.functions import *
from datetime import datetime

假设您的输入数据与我的df(DataFrame)相同

^{pr2}$

这是定义的函数

def previous_day(date, dayOfWeek):
    return date_sub(next_day(date, 'monday'), 7)

# Converting the string column to timestamp.
df = df.withColumn('scheduled_date', date_format(unix_timestamp('scheduled_date', 'MM/dd/yyy') \
       .cast('timestamp'), 'yyyy-MM-dd'))

df.show()
+ -+       +
| id|scheduled_date|
+ -+       +
|241|    2018-10-09|
|423|    2018-09-25|
|126|    2018-09-30|
|123|    2018-08-13|
|132|    2018-08-16|
|143|    2018-10-06|
+ -+       +

# Returns the first monday of a week
df_mon = df.withColumn("scheduled_date", previous_day('scheduled_date', 'monday'))

df_mon.show()
+ -+       +
| id|scheduled_date|
+ -+       +
|241|    2018-10-08|
|423|    2018-09-24|
|126|    2018-09-24|
|123|    2018-08-13|
|132|    2018-08-13|
|143|    2018-10-01|
+ -+       +

# You can groupBy and do agg count of 'id'.
df_mon_grp = df_mon.groupBy('scheduled_date').agg(count('id')).orderBy('scheduled_date')

# Reformatting to match your resulting output.
df_mon_grp = df_mon_grp.withColumn('scheduled_date', date_format(unix_timestamp('scheduled_date', "yyyy-MM-dd") \
                       .cast('timestamp'), 'MM/dd/yyyy'))

df_mon_grp.show()
+       +    -+
|scheduled_date|count(id)|
+       +    -+
|    08/13/2018|        2|
|    09/24/2018|        2|
|    10/01/2018|        1|
|    10/08/2018|        1|
+       +    -+

相关问题 更多 >

    热门问题