在pysp中使用用户定义函数时使用df.show()时出错

2024-09-28 21:51:47 发布

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

我有这个示例数据帧

import datetime
elevDF = sc.parallelize([
    (datetime.datetime(1984, 1, 1, 0, 0), 1, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 2, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 3, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 4, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 5, 638.55)
]).toDF(["date", "hour", "value"])

我想用这个列中的datetimes中的月份名称作为字符串生成一个df

这就是我试过的

## Creating udf function
import pyspark.sql.functions as F
from pyspark.sql.functions import month
from pyspark.sql.types import StringType
udfGetMonthName = F.udf(lambda col: month(col), StringType())

## Using udf function
elevDF.select(
    udfGetMonthName('date').alias('year')
).show()

但是,当我运行代码时,我得到以下错误

Py4JJavaError: An error occurred while calling o1407.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 86.0 failed 4 times, most recent failure: Lost task 0.3 in stage 86.0 (TID 645, spark-m.asia-south1-c.c.cp-vision-239212.internal, executor 1)

我查看了下面的链接建议,它表明这可能是一个实例问题(Issue with df.show() in pyspark)。重新启动内核,创建新实例。不起作用

有人能帮忙吗。非常感谢


Tags: infromimportdfsqldatetimedatefunction
1条回答
网友
1楼 · 发布于 2024-09-28 21:51:47

好吧,你不能在自定义项中使用pyspark本机函数。这是一种分发python函数的方法

但是,您可以尝试使用strftime来执行此操作,这是一个python datetime库函数:

elevUDF = F.udf(lambda x: x.strftime("%B"))

elevDF.withColumn("month_name", elevUDF("date")).show()
+         -+  +   +     +
|               date|hour| value|month_name|
+         -+  +   +     +
|1984-01-01 00:00:00|   1|638.55|   January|
|1984-01-01 00:00:00|   2|638.55|   January|
|1984-01-01 00:00:00|   3|638.55|   January|
|1984-01-01 00:00:00|   4|638.55|   January|
|1984-01-01 00:00:00|   5|638.55|   January|
+         -+  +   +     +

相关问题 更多 >