我有两个数组列(names
,score
)。我要把它们都炸掉。将名称作为得分的name
列(类似于pivot)
+------------+-------------------------+--------------------+
| id | names | score |
+------------+-------------------------+--------------------+
|ab01 |[F1 , F2, F3, F4, F5] |[00123, 000.001, 00127, 00.0123, 111]
|ab02 |[F1 , F2, F3, F4, F5, F6]|[00124, 000.003, 00156, 00.067, 156, 254]
|ab03 |[F1 , F2, F3, F4, F5] |[00234, 000.078, 00188, 00.0144, 188]
|ab04 |[F1 , F2, F3, F4, F5] |[00345, 000.01112, 001567, 00.0186, 555]
预期产出:
id F1 F2 F3 F4 F5 F6
ab01 00123 000.001 00127 00.0123 111 null
ab02 00124 000.003 00156 00.067 156 254
ab03 00234 000.078 00188 00.0144 188 null
ab04 00345 000.01112 001567 00.0186 555 null
我试着把名字和分数拉上拉链,然后把它们炸开
combine = F.udf(lambda x, y: list(zip(x, y)),
ArrayType(
StructType(
[StructField("names", StringType()),
StructField("score", StringType())
]
)
)
)
df2 = df.withColumn("new", combine("score", "names"))
.withColumn("new", F.explode("new"))
.select("id",
F.col("new.names").alias("names"),
F.col("new.score").alias("score")
)
我得到一个错误:
TypeError: zip argument #1 must support iteration
我还尝试使用rdd flatMap()
进行爆炸,但仍然得到相同的错误
有没有其他方法可以实现这一点
使用^{} 函数+
explode
,然后最后使用group by和pivot:对于Spark<;2.4:
您的UDF
combine
正常。出现错误TypeError: zip argument #1 must support iteration
,因为要将列名作为字符串传递给UDF,请使用col传递列:数据帧中可能有空值。在UDF中添加检查以确保不会发生这种情况
尝试:
df3:
编辑:
或
y:
相关问题 更多 >
编程相关推荐