在pyspark中将向量类型转换为双精度类型
Convert vector type to double type in pyspark
我有以下 spark 数据框:
+--------------------+--------------------+
| f1| f2|
+--------------------+--------------------+
| [380.1792652309408]|[-91793.40296983652]|
|[-18662.02751719936]|[-99674.18149372772]|
|[-736.5125444921572]| [-23736.3626879109]|
|[-143436.24812848...|[-136748.6250801389]|
|[-10325.057466551...|[-108747.85455021...|
|[-9771.868356757912]|[-164454.02688403...|
但我想将这些列中的值从向量类型转换为双精度
输出。我该怎么做?
示例输出:
+--------------------+--------------------+
| f1| f2|
+--------------------+--------------------+
| 380.1792652309408|-91793.40296983652|
|-18662.02751719936|-99674.18149372772|
|-736.5125444921572| -23736.3626879109|
|-143436.24812848...|-136748.6250801389|
|-10325.057466551...|-108747.85455021...|
|-9771.868356757912|-164454.02688403...|
更新了答案。由于我没有使用 Row,因此改进了原始答案。
在强制停机的情况下,在后台执行一些 pyspark 和机器学习的工作。这里重点关注基数 > 1 且所有行中的基数相同的 Vector ,这是有意义的。并重命名cols。
您现在可以使用这个例子:
%python
from pyspark.ml.linalg import Vectors
from pyspark.sql import Row
source_data = [
Row(city="AMS", temps=Vectors.dense([-1.0, -2.0, -3.0])),
Row(city="BRU", temps=Vectors.dense([-7.0, -7.0, -5.0])),
]
df = spark.createDataFrame(source_data)
def convertToCols(row):
return ( tuple(row.temps.toArray().tolist()))
df2 = df.rdd.map(convertToCols).toDF(["C1"])
df3 = df2.toDF(*(c.replace('_', 'C') for c in df2.columns))
df3.show()
returns:
+----+----+----+
| C1| C2| C3|
+----+----+----+
|-1.0|-2.0|-3.0|
|-7.0|-7.0|-5.0|
+----+----+----+
在我的示例中重要的是使用 Row 就像创建内嵌 DF 一样。
我有以下 spark 数据框:
+--------------------+--------------------+
| f1| f2|
+--------------------+--------------------+
| [380.1792652309408]|[-91793.40296983652]|
|[-18662.02751719936]|[-99674.18149372772]|
|[-736.5125444921572]| [-23736.3626879109]|
|[-143436.24812848...|[-136748.6250801389]|
|[-10325.057466551...|[-108747.85455021...|
|[-9771.868356757912]|[-164454.02688403...|
但我想将这些列中的值从向量类型转换为双精度 输出。我该怎么做?
示例输出:
+--------------------+--------------------+
| f1| f2|
+--------------------+--------------------+
| 380.1792652309408|-91793.40296983652|
|-18662.02751719936|-99674.18149372772|
|-736.5125444921572| -23736.3626879109|
|-143436.24812848...|-136748.6250801389|
|-10325.057466551...|-108747.85455021...|
|-9771.868356757912|-164454.02688403...|
更新了答案。由于我没有使用 Row,因此改进了原始答案。
在强制停机的情况下,在后台执行一些 pyspark 和机器学习的工作。这里重点关注基数 > 1 且所有行中的基数相同的 Vector ,这是有意义的。并重命名cols。
您现在可以使用这个例子:
%python
from pyspark.ml.linalg import Vectors
from pyspark.sql import Row
source_data = [
Row(city="AMS", temps=Vectors.dense([-1.0, -2.0, -3.0])),
Row(city="BRU", temps=Vectors.dense([-7.0, -7.0, -5.0])),
]
df = spark.createDataFrame(source_data)
def convertToCols(row):
return ( tuple(row.temps.toArray().tolist()))
df2 = df.rdd.map(convertToCols).toDF(["C1"])
df3 = df2.toDF(*(c.replace('_', 'C') for c in df2.columns))
df3.show()
returns:
+----+----+----+
| C1| C2| C3|
+----+----+----+
|-1.0|-2.0|-3.0|
|-7.0|-7.0|-5.0|
+----+----+----+
在我的示例中重要的是使用 Row 就像创建内嵌 DF 一样。