gpt4 book ai didi

python - 如何在pyspark中将DenseMatrix转换为spark DataFrame?

转载 作者:行者123 更新时间:2023-11-30 22:01:16 41 4
gpt4 key购买 nike

除了下面使用 Scala 的示例之外,我没有找到任何将矩阵转换为 Spark 数据帧的 pyspark 代码。有谁知道如何使用 python 代替吗?

How to convert a mllib matrix to a spark dataframe?

最佳答案

我们可以使用toArray()方法将DenseMatrix转换为numpy ndarray,并使用tolist()方法将数组转换为列表。

>>> m = DenseMatrix(2, 2, range(4))
>>> m
DenseMatrix(2, 2, [0.0, 1.0, 2.0, 3.0], False)
>>> rows = m.toArray().tolist()
>>> rows
[[0.0, 2.0], [1.0, 3.0]]
>>> df = spark.createDataFrame(rows,['col1','col2'])
>>> df.show()
+----+----+
|col1|col2|
+----+----+
| 0.0| 2.0|
| 1.0| 3.0|
+----+----+

关于python - 如何在pyspark中将DenseMatrix转换为spark DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103400/

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