0

到矢量我有一个表test_tbl:如何转换字符串的火花数据帧阵列中的蟒蛇

+-----------------+--------------+--------------+--+ 
| test_tbl.label | test_tbl.f1 | test_tbl.f2 | 
+-----------------+--------------+--------------+--+ 
| 0    | a   | b   | 
| 1    | c   | d   | 
+-----------------+--------------+--------------+--+ 

我想列F1和F2组合成具有以下pyspark代码矢量:

arr_to_vector = udf(lambda a: Vectors.dense(a), VectorUDT()) 
df = sqlContext.sql("""SELECT label,array(f1, f2) as features       
         FROM test_tbl""") 
df_vector = df.select(df["label"], 
arr_to_vector(df["features"]).alias("features")) 
df_vector.show() 

然后,我得到了错误: ValueError:使用序列设置数组元素。

然而,如果我改变在表中的F1的值和f2是号码,如(虽然列的数据类型被定义为字符串):

+-----------------+--------------+--------------+--+ 
| test_tbl.label | test_tbl.f1 | test_tbl.f2 | 
+-----------------+--------------+--------------+--+ 
| 0    | 0.1   | 0.2   | 
| 1    | 0.3   | 0.4   | 
+-----------------+--------------+--------------+--+ 

的误差消失,UDF工作正常。

任何人都可以帮忙吗?

回答

0

您可以考虑使用StringIndexer将分类变量转换为float。

https://spark.apache.org/docs/2.2.0/ml-features.html#stringindexer

from pyspark.ml.feature import StringIndexer 

df = spark.createDataFrame(
    [(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")], 
    ["id", "category"]) 

indexer = StringIndexer(inputCol="category", outputCol="categoryIndex") 
indexed = indexer.fit(df).transform(df) 
indexed.show() 
+0

你应该包括将回答这个问题使用的例子。链接死亡,然后你的答案将不提供任何信息。 – sorak