gpt4 book ai didi

python - 如何访问 Spark 稀疏向量元素

转载 作者:行者123 更新时间:2023-12-04 03:56:18 24 4
gpt4 key购买 nike

我有一个通过 OneHotEncoder 在 spark 数据框中获得的稀疏向量列,基本上看起来像这样显示前 10 行:

+------------------------------------+
|check_indexed_encoded |
+------------------------------------+
| (3,[2],[1.0])|
| (3,[0],[1.0])|
| (3,[2],[1.0])|
| (3,[2],[1.0])|
| (3,[2],[1.0])|
| (3,[2],[1.0])|
| (3,[2],[1.0])|
| (3,[2],[1.0])|
| (3,[2],[1.0])|
| (3,[0],[1.0])|
+------------------------------------+
only showing top 10 rows
我正在尝试访问这些元素,以将其基本上转换回(通常)热编码的假人,以便能够将整个帧毫无问题地转换为 Pandas。在 spark 中,我尝试使用 .GetItem 和 .element 但这也会引发错误消息“无法提取值:需要结构类型”。任何想法如何从中获取值?谢谢!

最佳答案

您可以使用 UDF。这应该这样做:

import pyspark.sql.functions as F
from pyspark.sql.types import DoubleType
from pyspark.sql.types import ArrayType

vector_udf = F.udf(lambda vector: vector.toArray().tolist(),ArrayType(DoubleType()))
df = df.withColumn("check_indexed_encoded_0", vector_udf(train["check_indexed_encoded"]).getItem(0))
要访问第二个元素,请使用 getItem(1) 等。

关于python - 如何访问 Spark 稀疏向量元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63843774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com