所有 data types in pyspark.sql.types
are :
__all__ = [
"DataType", "NullType", "StringType", "BinaryType", "BooleanType", "DateType",
"TimestampType", "DecimalType", "DoubleType", "FloatType", "ByteType", "IntegerType",
"LongType", "ShortType", "ArrayType", "MapType", "StructField", "StructType"]
我必须编写一个返回元组数组的 UDF(在 pyspark 中)。我给它的第二个参数是什么,它是 udf 方法的返回类型?这将类似于 ArrayType(TupleType())
...
最佳答案
Spark 中没有 TupleType
这样的东西。产品类型表示为具有特定类型字段的结构
。例如,如果你想返回一个数组对(整数,字符串),你可以使用这样的模式:
from pyspark.sql.types import *
schema = ArrayType(StructType([
StructField("char", StringType(), False),
StructField("count", IntegerType(), False)
]))
示例用法:
from pyspark.sql.functions import udf
from collections import Counter
char_count_udf = udf(
lambda s: Counter(s).most_common(),
schema
)
df = sc.parallelize([(1, "foo"), (2, "bar")]).toDF(["id", "value"])
df.select("*", char_count_udf(df["value"])).show(2, False)
## +---+-----+-------------------------+
## |id |value|PythonUDF#<lambda>(value)|
## +---+-----+-------------------------+
## |1 |foo |[[o,2], [f,1]] |
## |2 |bar |[[r,1], [a,1], [b,1]] |
## +---+-----+-------------------------+
关于python - 如何在 PySpark 的 UDF 中返回 "Tuple type"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36840563/