【问题标题】:Convert PySpark Dense Column Vectors into Rows [duplicate]将 PySpark 密集列向量转换为行 [重复]
【发布时间】:2019-05-18 13:55:28
【问题描述】:

我有一个包含 3 列的数据框,每个条目都是相同长度的密集向量。 如何融化 Vector 条目?

当前数据框:

第 1 列 |第 2 列 |

[1.0,2.0,3.0]|[10.0,4.0,3.0]

[5.0,4.0,3.0]|[11.0,26.0,3.0]

[9.0,8.0,7.0]|[13.0,7.0,3.0]

预期:

column1|column2

1.0 。 10.0

2.0 。 4.0

3.0 。 3.0

5.0 。 11.0

4.0 。 26.0

3.0 。 3.0

9.0 。 13.0

...

【问题讨论】:

    标签: pyspark apache-spark-sql melt


    【解决方案1】:

    第 1 步:让我们创建初始 DataFrame:

    myValues = [([1.0,2.0,3.0],[10.0,4.0,3.0]),([5.0,4.0,3.0],[11.0,26.0,3.0]),([9.0,8.0,7.0],[13.0,7.0,3.0])]
    df = sqlContext.createDataFrame(myValues,['column1','column2'])
    df.show()
    +---------------+-----------------+
    |        column1|          column2|
    +---------------+-----------------+
    |[1.0, 2.0, 3.0]| [10.0, 4.0, 3.0]|
    |[5.0, 4.0, 3.0]|[11.0, 26.0, 3.0]|
    |[9.0, 8.0, 7.0]| [13.0, 7.0, 3.0]|
    +---------------+-----------------+
    

    第 2 步: 现在,explode 两列,但在我们 zip 之后是数组。这里我们事先知道list/array的长度是3。

    from pyspark.sql.functions import array, struct
    tmp = explode(array(*[
        struct(col("column1").getItem(i).alias("column1"), col("column2").getItem(i).alias("column2"))
        for i in range(3)
    ]))
    df=(df.withColumn("tmp", tmp).select(col("tmp").getItem("column1").alias('column1'), col("tmp").getItem("column2").alias('column2')))
    df.show()
    +-------+-------+
    |column1|column2|
    +-------+-------+
    |    1.0|   10.0|
    |    2.0|    4.0|
    |    3.0|    3.0|
    |    5.0|   11.0|
    |    4.0|   26.0|
    |    3.0|    3.0|
    |    9.0|   13.0|
    |    8.0|    7.0|
    |    7.0|    3.0|
    +-------+-------+
    

    【讨论】:

    • 谢谢!这真的很有帮助。
    • 不用担心。你能接受它作为答案吗?
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2019-03-03
    • 2018-12-15
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多