在 PySpark 中转置 RowMatrix

Pat*_*uff 4 python apache-spark pyspark

您好,我想知道如何在 PySpark 中转置 RowMatrix。

data = [(MLLibVectors.dense([1.0, 2.0]), ), (MLLibVectors.dense([3.0, 4.0]), )]

df=sqlContext.createDataFrame(data, ["features"])
features=df.select("features").rdd.map(lambda row: row[0])

mat=RowMatrix(features)
print mat.rows.first()
#[1.0,2.0]

mat=mat.Transpose()

print mat.rows.first()
#[1.0,3.0]
Run Code Online (Sandbox Code Playgroud)

有人用Python实现这个吗?我看过类似的帖子,但一切都在 Scala 中。谢谢。

Psi*_*dom 5

RowMatrix没有transpose方法。您可能需要一个BlockMatrixCooperativeMatrix


from pyspark.mllib.linalg.distributed import CoordinateMatrix, MatrixEntry

cm = CoordinateMatrix(
    mat.rows.zipWithIndex().flatMap(
        lambda x: [MatrixEntry(x[1], j, v) for j, v in enumerate(x[0])]
    )
)

cm.toRowMatrix().rows.first().toArray()
# array([ 1.,  2.])

cm.transpose().toRowMatrix().rows.first().toArray()
# array([ 1.,  3.])
Run Code Online (Sandbox Code Playgroud)