Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将spark字符串列转换为vectorUDT_Python_Dataframe_Apache Spark_Pyspark - Fatal编程技术网

Python 将spark字符串列转换为vectorUDT

Python 将spark字符串列转换为vectorUDT,python,dataframe,apache-spark,pyspark,Python,Dataframe,Apache Spark,Pyspark,我正在使用pyspark。 首先,我读取一个带有字符串列的csv。其中的数据如下所示: (174、[7,10,56,89,156]、[1.0,1.0,1.0,1.0,1.0,1.0]) 我需要把它转换成一个向量,把这个列作为机器学习算法的输入。 我已经试过投专栏: data=data.withColumn(列,data[column].cast(VectorUDT()) 但它不起作用。。。 您有什么解决方案吗?您可以尝试的一种方法是使用VectorUDT的内部(见下文)构造一个JSON字符

我正在使用pyspark。
首先,我读取一个带有字符串列的csv。其中的数据如下所示:

(174、[7,10,56,89,156]、[1.0,1.0,1.0,1.0,1.0,1.0])

我需要把它转换成一个向量,把这个列作为机器学习算法的输入。

我已经试过投专栏:

data=data.withColumn(列,data[column].cast(VectorUDT())

但它不起作用。。。


您有什么解决方案吗?

您可以尝试的一种方法是使用VectorUDT的内部(见下文)构造一个JSON字符串,然后使用
from_JSON
函数:

struct<type:tinyint,size:int,indices:array<int>,values:array<double>> 
注意我们在这里构建的JSON字符串是一个带有单个VectorUDT的数组,然后我们可以使用
from_JSON
getItem(0)
来检索向量

结果:
from pyspark.ml.linalg import VectorUDT
from pyspark.sql.types import ArrayType
from pyspark.sql.functions import expr, from_json

df = spark.createDataFrame([('(174, [7, 10, 56, 89, 156], [1.0, 1.0, 1.0, 1.0, 1.0])',)],['column'])
# DataFrame[column: string]

df_new = df.withColumn("s", expr("split(substr(column,2,length(column)-2), ',\\\\s*(?=\\\\[)')")) \
  .selectExpr("""
      concat(
        /* type = 0 for SparseVector and type = 1 for DenseVector */
        '[{"type":0,"size":',
        s[0],
        ',"indices":',
        s[1],
        ',"values":',
        s[2],
        '}]'
      ) as vec_json
   """) \
  .withColumn('features', from_json('vec_json', ArrayType(VectorUDT()))[0])
df_new.printSchema()
root
 |-- vec_json: string (nullable = true)
 |-- features: vector (nullable = true)

df_new.show(truncate=False, vertical=True)
-RECORD 0---------------------------------------------------------------------------------------------
 vec_json | [{"type":0,"size":174,"indices":[7, 10, 56, 89, 156],"values":[1.0, 1.0, 1.0, 1.0, 1.0]}]
 features | (174,[7,10,56,89,156],[1.0,1.0,1.0,1.0,1.0])