Hun*_*nle 12 python user-defined-functions apache-spark apache-spark-sql pyspark
我有一个udf返回一个字符串列表.这不应该太难.我在执行udf时传入数据类型,因为它返回一个字符串数组: ArrayType(StringType).
现在,不知怎的,这不起作用:
我正在操作的数据帧是df_subsets_concat,看起来像这样:
df_subsets_concat.show(3,False)
Run Code Online (Sandbox Code Playgroud)
+----------------------+
|col1 |
+----------------------+
|oculunt |
|predistposed |
|incredulous |
+----------------------+
only showing top 3 rows
Run Code Online (Sandbox Code Playgroud)
而代码是
from pyspark.sql.types import ArrayType, FloatType, StringType
my_udf = lambda domain: ['s','n']
label_udf = udf(my_udf, ArrayType(StringType))
df_subsets_concat_with_md = df_subsets_concat.withColumn('subset', label_udf(df_subsets_concat.col1))
Run Code Online (Sandbox Code Playgroud)
结果是
/usr/lib/spark/python/pyspark/sql/types.py in __init__(self, elementType, containsNull)
288 False
289 """
--> 290 assert isinstance(elementType, DataType), "elementType should be DataType"
291 self.elementType = elementType
292 self.containsNull = containsNull
AssertionError: elementType should be DataType
Run Code Online (Sandbox Code Playgroud)
我的理解是,这是正确的方法.以下是一些资源: pySpark Data Frames"assert isinstance(dataType,DataType),"dataType应该是DataType" 如何在PySpark中的UDF中返回"Tuple类型"?
但这些都没有帮助我解决为什么这不起作用.我正在使用pyspark 1.6.1.
如何在pyspark中创建一个返回字符串数组的udf?
Psi*_*dom 23
您需要初始化一个StringType实例:
label_udf = udf(my_udf, ArrayType(StringType()))
# ^^
df.withColumn('subset', label_udf(df.col1)).show()
+------------+------+
| col1|subset|
+------------+------+
| oculunt|[s, n]|
|predistposed|[s, n]|
| incredulous|[s, n]|
+------------+------+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15971 次 |
| 最近记录: |