只有当结果数据可以放入您的主内存时,您的请求才有意义(即您可以安全地使用collect());另一方面,如果是这样的话,诚然你完全没有理由使用 Spark。
无论如何,鉴于此假设,这是使用玩具数据将单列 features Spark 数据帧(Rows of DenseVector)转换为 NumPy 数组的通用方法:
spark.version
# u'2.2.0'
from pyspark.ml.linalg import Vectors
import numpy as np
# toy data:
df = spark.createDataFrame([(Vectors.dense([0,45,63,0,0,0,0]),),
(Vectors.dense([0,0,0,85,0,69,0]),),
(Vectors.dense([0,89,56,0,0,0,0]) ,),
], ['features'])
dd = df.collect()
dd
# [Row(features=DenseVector([0.0, 45.0, 63.0, 0.0, 0.0, 0.0, 0.0])),
# Row(features=DenseVector([0.0, 0.0, 0.0, 85.0, 0.0, 69.0, 0.0])),
# Row(features=DenseVector([0.0, 89.0, 56.0, 0.0, 0.0, 0.0, 0.0]))]
np.asarray([x[0] for x in dd])
# array([[ 0., 45., 63., 0., 0., 0., 0.],
# [ 0., 0., 0., 85., 0., 69., 0.],
# [ 0., 89., 56., 0., 0., 0., 0.]])