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

Gav*_*vin 1 python apache-spark apache-spark-sql

除了以下使用 Scala 的示例外,我没有找到任何 pyspark 代码来将矩阵转换为火花数据帧。有谁知道如何改用python?

如何将 mllib 矩阵转换为 spark 数据帧?

Sur*_*esh 5

我们可以使用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|
+----+----+
Run Code Online (Sandbox Code Playgroud)