datetime - Pyspark 通过列表理解从日期时间获取时间属性
问题描述
我有一个 pyspark 数据框 df:
+-------------------+
| timestamplast|
+-------------------+
|2019-08-01 00:00:00|
|2019-08-01 00:01:09|
|2019-08-01 01:00:20|
|2019-08-03 00:00:27|
+-------------------+
我想通过列表理解将列 'year','month','day','hour' 添加到现有数据框中。
在 Pandas 中,这将是这样完成的:
L = ['year', 'month', 'day', 'hour']
date_gen = (getattr(df['timestamplast'].dt, i).rename(i) for i in L)
df = df.join(pd.concat(date_gen, axis=1)) # concatenate results and join to original dataframe
这将如何在 pyspark 中完成?
解决方案
检查以下内容:
df.selectExpr("*", *[ '{0}(timestamplast) as {0}'.format(c) for c in L]).show()
+-------------------+----+-----+---+----+
| timestamplast|year|month|day|hour|
+-------------------+----+-----+---+----+
|2019-08-01 00:00:00|2019| 8| 1| 0|
|2019-08-03 00:00:27|2019| 8| 3| 0|
+-------------------+----+-----+---+----+
推荐阅读
- javascript - 为什么我没有成功输出简单的 js 算法?
- ios - 如何检索 MTKView/UIView/NSView 使用的当前纹理
- javascript - 将 .then() 内部的字符串作为 JSX 元素解析到外部
- c++ - 获取剪贴板 signal_owner_change 源自的 GTK 窗口 (Gtkmm)
- python - Python:如何将函数分配给变量?
- php - PHP Twitter API 分块上传问题:段加起来不等于提供的总文件大小
- php - 如何从 Laravel 6 中的包中覆盖应用程序路由
- python - 当一个类的任何属性被修改时,它如何运行某个函数?
- c++ - 容器类内部的类迭代器
- swift - 使用 SwiftUI 启动 TextField 时出现 VStack 错误