pyspark - 将包含数组的数据框重新格式化为 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 行。
解决方案
这是你想要做的吗?讨厌使用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]
推荐阅读
- vb.net - 在 vb.net 中单击按钮打印时,如何从表单中的数据库访问中提取数据并在另一个表单上显示为收据
- c# - 解析Json递归的方法
- python - 线性数据的正则多项式回归 - 仅惩罚 2 次系数
- python - 如何将外部 NLP 技术集成到 Dialogflow?
- javascript - 浏览器的音频记录或麦克风对按钮单击而不是页面加载的权限
- docker - 如何通过 dotnet sdk 将 .dcproj 添加到解决方案中
- node.js - 使用 $graphLookup 的 Mongo 分层查询能够处理三个级别但需要多个级别
- react-native - 反应本机 axios 调用抛出 403 但邮递员正确输出数据
- python - 在numpy数组中按值选择性删除
- sequence - 使用正数和负数重复模 -1 到 1 的数字