如何从两个列表创建 PySpark 数据框?

How to create a PySpark dataframe from two lists?

我正在研究 Databricks,并希望使用 Python 在 Spark 中使用 MLlib 包。当我以前使用 Scikit-learn 时,我会有一个特征列表,以及另一个特征标签列表。我会简单地使用决策树分类器和预测来适应它。

查看文档,我对如何在 PySpark 上做类似的事情有点迷茫:https://docs.databricks.com/spark/latest/mllib/binary-classification-mllib-pipelines.html

我相信为了使用 MLlib,我需要从数据框中提取列以用作特征和标签。所以在这样做的时候,我想知道如何创建一个新的空数据框,然后向其添加两列,一列是特征列表,另一列是标签列表。

我的特征列表(例如:[2、0、0、1])称为 'ml_list',我的标签列表(例如:[1] 或 [0])称为 'labels'.

到目前为止,这是我的代码,不确定我是否走在正确的道路上。我的特征和标签都是二进制的,所以我选择了 IntegerType():

field = [StructField(“ml_list”,IntegerType(), 
True),StructField(“Labels”, IntegerType(), True)]

schema = StructType(field)
df_date = sqlContext.createDataFrame(sc.emptyRDD(), schema)

任何帮助都会很棒,因为我对 Spark 还很陌生。

如果你有:

labels = [[0], [1], [0]]

features = [[2, 0, 0, 1], [0, 0, 0, 1], [0, 2, 0, 1]]

您可以:

from pyspark.ml.linalg import Vectors

sc.parallelize(zip(labels, features)).map(lambda lp: (float(lp[0][0]), Vectors.dense(lp[1]))).toDF(["label", "features"])

或者:

from pyspark.ml.linalg import Vectors

dd = [(labels[i][0], Vectors.dense(features[i])) for i in range(len(labels))]
df = spark.createDataFrame(sc.parallelize(dd),schema=["label", "features"])