首页 > 解决方案 > 将包含数组的数据框重新格式化为 RowMatrix

问题描述

我有以下格式的数据框:

+----+-----+
| features |
+----+-----+
|[1,4,7,10]|
|[2,5,8,11]|
|[3,6,9,12]|
+----+----+

创建示例数据框的脚本:

rows2 = sc.parallelize([ IndexedRow(0, [1, 4, 7, 10 ]),
                         IndexedRow(1, [2, 5, 8, 1]),
                         IndexedRow(1, [3, 6, 9, 12]),
                                   ])
rows_df = rows2.toDF()
row_vec= rows_df.drop("index")
row_vec.show()

特征列包含 4 个特征,并且有 3 个行 ID。我想将此数据转换为行矩阵,其中的列和行将采用以下 mat 格式:

from pyspark.mllib.linalg.distributed import RowMatrix
rows = sc.parallelize([(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)])

# Convert to RowMatrix
mat = RowMatrix(rows)

# Calculate exact and approximate similarities
exact = mat.columnSimilarities()
approx = mat.columnSimilarities(0.05) 

基本上,我想将数据帧转换为新格式,以便我可以运行 columnSimilarities() 函数。我有一个更大的数据框,其中包含 50 个特征和 39000 行。

标签: pyspark

解决方案


这是你想要做的吗?讨厌使用collect(),但不认为在这里可以避免,因为您想将结构化对象重塑/转换为矩阵......对吗?

X = np.array(row_vec.select("_2").collect()).reshape(-1,3)
X = sc.parallelize(X)
for i in X.collect(): print(i)
[1 4 7]
[10  2  5]
[8 1 3]
[ 6  9 12]

推荐阅读