使用Pyspark将密集向量转换为数据框

时间:2018-09-27 21:32:24

标签: python pandas apache-spark dataframe

首先,我尝试了下面链接中的所有内容来修复我的错误,但没有一个起作用。

How to convert RDD of dense vector into DataFrame in pyspark?

我正在尝试将密集向量与列名一起转换为数据帧(最好是Spark),并遇到问题。

我在spark数据框中的列是一个使用Vector Assembler创建的向量,现在我想将其转换回数据框架,因为我想在向量中的某些变量上创建图。

方法1:

from pyspark.ml.linalg import SparseVector, DenseVector
from pyspark.ml.linalg import Vectors

temp=output.select("all_features")
temp.rdd.map(
    lambda row: (DenseVector(row[0].toArray()))
).toDF()

下面是错误

TypeError: not supported type: <type 'numpy.ndarray'>

方法2:

from pyspark.ml.linalg import VectorUDT
from pyspark.sql.functions import udf
from pyspark.ml.linalg import *

as_ml = udf(lambda v: v.asML() if v is not None else None, VectorUDT())
result = output.withColumn("all_features", as_ml("all_features"))
result.head(5)

错误:

AttributeError: 'numpy.ndarray' object has no attribute 'asML'

我还尝试将数据框转换为Pandas数据框,然后无法将值拆分为单独的列

方法3:

pandas_df=temp.toPandas()
pandas_df1=pd.DataFrame(pandas_df.all_features.values.tolist())

上面的代码运行良好,但我的数据框中仍然只有一列,所有值都用逗号分隔为列表。

非常感谢您的帮助!

编辑:

这是我的临时数据帧的外观。它只有一列all_features。我正在尝试创建一个将所有这些值拆分为单独列的数据框(all_features是使用200列创建的向量)

+--------------------+
|        all_features|
+--------------------+
|[0.01193689934723...|
|[0.04774759738895...|
|[0.0,0.0,0.194417...|
|[0.02387379869447...|
|[1.89796699621085...|
+--------------------+
only showing top 5 rows

期望的输出是一个数据帧,其中所有200列都在一个数据帧中分开

+----------------------------+
|        col1| col2| col3|...
+----------------------------+
|0.01193689934723|0.0|0.5049431301173817...
|0.04774759738895|0.0|0.1657316216149636...
|0.0|0.0|7.213126372469...
|0.02387379869447|0.0|0.1866693496827619|...
|1.89796699621085|0.0|0.3192169213385746|...
+----------------------------+
only showing top 5 rows

这是我的熊猫DF输出的样子

              0
0   [0.011936899347238104, 0.0, 0.5049431301173817...
1   [0.047747597388952415, 0.0, 0.1657316216149636...
2   [0.0, 0.0, 0.19441761495525278, 7.213126372469...
3   [0.023873798694476207, 0.0, 0.1866693496827619...
4   [1.8979669962108585, 0.0, 0.3192169213385746, ...

1 个答案:

答案 0 :(得分:2)

由于您希望所有功能都位于不同的列中(如我从EDIT中所获得的那样),因此提供给您答案的链接不是您的解决方案。

尝试一下

#column_names
temp = temp.rdd.map(lambda x:[float(y) for y in x['all_features']]).toDF(column_names)

编辑:

由于temp最初是一个数据帧,因此您也可以使用此方法而无需将其转换为rdd

import pyspark.sql.functions as F
from pyspark.sql.types import *

splits = [F.udf(lambda val: float(val[i].item()),FloatType()) for i in range(200)]
temp = temp.select(*[s(F.col('all_features')).alias(c) for c,s in zip(column_names,splits)])
temp.show()