pyspark:将DataFrame行合并到DenseVector中

时间:2016-05-04 17:36:31

标签: apache-spark pyspark spark-dataframe pyspark-sql

我有一个DataFrame,有两列:

df = sqlContext.createDataFrame([
    (1, 'a'), (2, 'a'),
    (3, 'b'), (4, 'b'),
    (5, 'c'), (6, 'c'),
    (7, 'd'), (8, 'd'),
], schema=['value', 'name'])

编辑2017/01/13: 我基于Entity-Attribute-Value模型从SQL表中派生出这个数据帧。所以另外一个第三个实体列" id"可用于每一行。

我想将其转换为"功能" DataFrame包的分类器所要求的ml。对于单个列,可以使用VectorAssembler

来实现
from pyspark.ml.feature import VectorAssembler

assembler = VectorAssembler(inputCols=['value'], outputCol="features")
selected_features = assembler.transform(df).select('features')
selected_features.collect()

[Row(features=DenseVector([1.0])),
 Row(features=DenseVector([2.0])),
 Row(features=DenseVector([3.0])),
 Row(features=DenseVector([4.0])),
 Row(features=DenseVector([5.0])),
 Row(features=DenseVector([6.0])),
 Row(features=DenseVector([7.0])),
 Row(features=DenseVector([8.0]))]

我想要的是:

[Row(features=DenseVector([1.0, 2.0])),
 Row(features=DenseVector([3.0, 4.0])),
 Row(features=DenseVector([5.0, 6.0])),
 Row(features=DenseVector([7.0, 8.0]))]

根据列value的值,将列DenseVector的值合并到name中的最有效方法是什么?

我在考虑GroupedData的自定义聚合函数的示例,它可以与groupby一起使用:

df.groupby('name').vector_agg().collect()

类似于PostgreSQL array_agg函数:

SELECT array_agg(df.value) FROM table as df
GROUP BY df.name;

2 个答案:

答案 0 :(得分:2)

我认为您的问题定义不明确,因为对于固定的name,无法知道哪个value属于哪一列。 ml包中的分类器都要求在训练样本之间一致地使用每列。在您的示例中,列恰好按所需顺序提供,但实际上您无法依赖此列。

如果您可以提供功能索引并从以下内容开始,您的问题就可以解决:

df = sc.sql.createDataFrame([
    ('a', ('f1', 1)), ('a', ('f2', 2)),
    ('b', ('f1', 3)), ('b', ('f2', 4)),
    ('c', ('f1', 5)), ('c', ('f2', 6)),
    ('d', ('f1', 7)), ('d', ('f2', 8)),
], schema=['name', 'feature'])

首先,按name分组并将您的功能汇总为列表:

import pyspark.sql.functions as F

df.groupBy('name')\
  .agg(F.collect_list('feature'))\
  .show()

输出:

+----+---------------------+
|name|collect_list(feature)|
+----+---------------------+
|   d|     [[f1,7], [f2,8]]|
|   c|     [[f1,5], [f2,6]]|
|   b|     [[f1,3], [f2,4]]|
|   a|     [[f1,1], [f2,2]]|
+----+---------------------+

接下来,使用withColumn中的udf将此数组转换为DenseVector。把它们放在一起:

from pyspark.ml.linalg import Vectors, VectorUDT
import pyspark.sql.functions as F

list_to_dense = F.udf(lambda l: Vectors.dense([v for (k,v) in sorted(l)]), VectorUDT())

df.groupBy('name')\
  .agg(F.collect_list('features'))\
  .withColumn('features', list_to_dense('collect_list(features)'))\
  .select('features')\
  .collect()

输出:

[Row(features=DenseVector([7.0, 8.0])),
 Row(features=DenseVector([5.0, 6.0])),
 Row(features=DenseVector([3.0, 4.0])),
 Row(features=DenseVector([1.0, 2.0]))]

答案 1 :(得分:1)

从您的数据结构中,您只需要使用相同的表格joinfilter values相同(或反转)的行。

df = sqlContext.createDataFrame([
    (1, 'a'), (2, 'a'),
    (3, 'b'), (4, 'b'),
    (5, 'c'), (6, 'c'),
    (7, 'd'), (8, 'd'),
], schema=['value', 'name'])

xf = df.select(df["name"].alias("nam"), df["value"].alias("val"))
pf = df.join(xf, df["name"] == xf["nam"], "inner").where(xf["val"] < df["value"]).select(df["value"], xf["val"], df["name"])

from pyspark.ml.feature import VectorAssembler


assembler = VectorAssembler(inputCols=['value', "val"], outputCol="features")
selected_features = assembler.transform(pf).select('features')
selected_features.collect()


#[Row(features=DenseVector([2.0, 1.0])),
# Row(features=DenseVector([4.0, 3.0])),
# Row(features=DenseVector([6.0, 5.0])),
# Row(features=DenseVector([8.0, 7.0]))]