Pyspark - 将datetime.time函数应用于所有数据帧行

时间:2018-05-15 10:18:15

标签: python datetime dataframe pyspark

我正在使用pyspark,我有一个带有两个int值的数据框,对应于小时和分钟:

+------------------------+----------------------+
|HOURS                   |                   MIN|
+------------------------+----------------------+
|                       9|                    25|
|                      22|                     5|
|                      22|                     5|
|                      22|                     5|
+------------------------+----------------------+

我想使用以下代码创建datetime类型的新列:

import datetime as dt
data = data.withColumn('TIME', dt.time(data["HOURS"], data["MIN"]))

但我得到以下错误:

TypeError: an integer is required

如何解决?非常感谢你:)

1 个答案:

答案 0 :(得分:1)

您将Column类型的广告传递给dt.time,因此dt.time会提升TypeError。您需要将python函数包装到用户定义函数(UDF)中以将类型Column传递给python函数:

import pandas as pd
import datetime as dt
from pyspark.sql.functions import udf


df = pd.DataFrame({"HOURS": [2, 5, 8], 
                   "MIN": [23, 55, 43]})

dfs = sqlContext.createDataFrame(df)
dfs.show()

+-----+---+
|HOURS|MIN|
+-----+---+
|    2| 23|
|    5| 55|
|    8| 43|
+-----+---+

@udf
def create_timestamp(hour, minute):
    return dt.time(hour, minute)

dfs.withColumn('TIME', create_timestamp("HOURS", "MIN")).show()

+-----+---+--------------------+
|HOURS|MIN|                TIME|
+-----+---+--------------------+
|    2| 23|Time: 2 hours, 23...|
|    5| 55|Time: 5 hours, 55...|
|    8| 43|Time: 8 hours, 43...|
+-----+---+--------------------+