【发布时间】:2019-11-01 23:46:00
【问题描述】:
我有一个 libsvm 格式的专栏(火花的毫升库)field1:value field2:value ...
+--------------+-----+
| features|label|
+--------------+-----+
| a:1 b:2 c:3| 0|
| a:4 b:5 c:6| 0|
| a:7 b:8 c:9| 1|
|a:10 b:11 c:12| 0|
+--------------+-----+
我想提取值并将它们保存在 pyspark 中每一行的数组中
features.printSchema()
root
|-- features: string (nullable = false)
|-- label: integer (nullable = true)
我正在使用以下 udf,因为受影响的列是数据框的一部分
from pyspark.sql.functions import udf
from pyspark.ml.linalg import Vectors
features_expl = udf(lambda features: Vectors.dense(features.split(" ")).map(lambda feat: float(str(feat.split(":")[1]))))
features=features.withColumn("feats", features_expl(features.features))
我得到的结果是: ValueError:无法将字符串转换为浮点数:移动:0.0 它似乎没有执行第二次拆分并在字符串上调用 float()。
我想得到的是:
+--------------+-----+
| features|label|
+--------------+-----+
| [1, 2, 3]| 0|
| [4, 5, 6]| 0|
| [7, 8, 9]| 1|
| [10, 11, 12]| 0|
+--------------+-----+
【问题讨论】:
标签: apache-spark pyspark apache-spark-sql pyspark-sql apache-spark-ml