如何使用pyspark从月中的某天开始获得工作日 [英] How to get the weekday from day of month using pyspark

查看:115
本文介绍了如何使用pyspark从月中的某天开始获得工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框log_df:

I have a dataframe log_df:

我根据以下代码生成一个新的数据框:

I generate a new dataframe based on the following code:

from pyspark.sql.functions import split, regexp_extract 
split_log_df = log_df.select(regexp_extract('value', r'^([^\s]+\s)', 1).alias('host'),
                          regexp_extract('value', r'^.*\[(\d\d/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} -\d{4})]', 1).alias('timestamp'),
                          regexp_extract('value', r'^.*"\w+\s+([^\s]+)\s+HTTP.*"', 1).alias('path'),
                          regexp_extract('value', r'^.*"\s+([^\s]+)', 1).cast('integer').alias('status'),
                          regexp_extract('value', r'^.*\s+(\d+)$', 1).cast('integer').alias('content_size'))
split_log_df.show(10, truncate=False)

新数据框如下所示:

我需要另一列显示星期几,创建它的最佳方式是什么?理想情况下,只需在select中添加类似udf的字段即可.

I need another column showing the dayofweek, what would be the best elegant way to create it? ideally just adding a udf like field in the select.

非常感谢您.

已更新:我的问题与注释中的问题不同,我需要的是基于log_df中的字符串进行计算,而不是基于注释中的时间戳,因此这不是重复的问题.谢谢.

Updated: my question is different than the one in the comment, what I need is to make the calculation based on a string in log_df, not based on the timestamp like the comment, so this is not a duplicate question. Thanks.

推荐答案

我终于自己解决了这个问题,下面是完整的解决方案:

I finally resolved the question myself, here is the complete solution:

  1. 导入date_format,datetime,DataType
  2. 首先,修改正则表达式以提取1995年7月1日
  3. 使用func将1995年7月1日转换为DateType
  4. 创建一个udf dayOfWeek以简短格式(星期一,星期二...)获取星期几
  5. 使用udf将DateType 01/Jul/1995转换为工作日,即Sat

我对我的解决方案不满意,因为它看起来像锯齿形,如果有人可以提出一个更优雅的解决方案,我将不胜感激,

I am not satisfied with my solution as it seems to be so zig-zag, it would be appreciated if anyone can come up with a more elegant solution, thank you in advance.

这篇关于如何使用pyspark从月中的某天开始获得工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆