【问题标题】:PySpark: extract values from from struct typePySpark:从结构类型中提取值
【发布时间】:2020-12-08 00:59:56
【问题描述】:

我有一个 Spark 数据框,其中一列(称为 features)是结构类型,具体来说:

struct<type:tinyint,size:int,indices:array<int>,values:array<double>>

当我执行df.printSchema() 时,我得到的是:

root
 |-- features: vector (nullable = true)

我想做的是将上述结构的values 放在单独的列中。

我试过了:

df.select("features.values").show()

然后我得到错误:

AnalysisException: Can't extract value from features#125369: need struct type but got struct<type:tinyint,size:int,indices:array<int>,values:array<double>>;

我不明白,尤其是上面写着need struct type but got struct (??) 的部分。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql


    【解决方案1】:

    您可能需要先将向量转换为数组:

    from pyspark.ml.functions import vector_to_array
    
    df2 = df.select(vector_to_array("features").alias("features"))
    

    然后选择适当的列。

    【讨论】:

    • 嗨@mck,感谢您的回答。我尝试了这个函数,但我似乎得到了一个与features 列的values 数组中的数组不同的数组。这是 1 行的示例:featuresvalues 数组包含:[1, 0.5, 1, 1, 1, 1, 1, 1, 0.5, 1],但“新”功能(应用 vector_to_array 后)包含:[1, 0, 0.5, 0, 0, 0, 0, 0, 0, 0]。你知道为什么这不是同一个数组吗?我似乎找不到有关此功能的任何好的文档。
    • @vdvaxel 这很奇怪,但我不能在没有看到一些代码的情况下说什么
    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 2021-04-10
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    相关资源
    最近更新 更多