我正在使用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
如何解决?非常感谢你:)
答案 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...|
+-----+---+--------------------+