我处理的数据帧有三列,colA、colB和colC
+---+-----+-----+-----+
|id |colA |colB |colC |
+---+-----+-----+-----+
| 1 | 5 | 8 | 3 |
| 2 | 9 | 7 | 4 |
| 3 | 3 | 0 | 6 |
| 4 | 1 | 6 | 7 |
+---+-----+-----+-----+
我需要合并colA、colB和colC列,以获得如下新的dataFrame:
+---+--------------+
|id | colD |
+---+--------------+
| 1 | [5, 8, 3] |
| 2 | [9, 7, 4] |
| 3 | [3, 0, 6] |
| 4 | [1, 6, 7] |
+---+--------------+
这是pyspark代码获得的第一个DataFrame:
l=[(1,5,8,3),(2,9,7,4), (3,3,0,6), (4,1,6,7)]
names=["id","colA","colB","colC"]
db=sqlContext.createDataFrame(l,names)
db.show()
如何将行转换为矢量?有人能帮我吗?感谢
您可以使用pyspark.ml、中的vectorassemblyr
from pyspark.ml.feature import VectorAssembler
newdb = VectorAssembler(inputCols=["colA", "colB", "colC"], outputCol="colD").transform(db)
newdb.show()
+---+----+----+----+-------------+
| id|colA|colB|colC| colD|
+---+----+----+----+-------------+
| 1| 5| 8| 3|[5.0,8.0,3.0]|
| 2| 9| 7| 4|[9.0,7.0,4.0]|
| 3| 3| 0| 6|[3.0,0.0,6.0]|
| 4| 1| 6| 7|[1.0,6.0,7.0]|
+---+----+----+----+-------------+
或者如果你愿意,可以使用udf进行逐行合成,
from pyspark.sql import functions as F
from pyspark.sql.types import *
udf1 = F.udf(lambda x,y,z : [x,y,z],ArrayType(IntegerType()))
df.select("id",udf1("colA","colB","colC").alias("colD")).show()
+---+---------+
| id| colD|
+---+---------+
| 1|[5, 8, 3]|
| 2|[9, 7, 4]|
| 3|[3, 0, 6]|
| 4|[1, 6, 7]|
+---+---------+
希望这能有所帮助。!
它实际上略微取决于您想要colD
的数据类型。如果需要VectorUDT
列,则使用VectorAssembler
是正确的转换。如果您只想将字段组合成一个数组,那么UDF是不必要的。您可以使用内置的array
函数来组合列:
>>> from pyspark.sql.functions import array
>>> db.select('id',array('colA','colB','colC').alias('colD')).show()
+---+---------+
| id| colD|
+---+---------+
| 1|[5, 8, 3]|
| 2|[9, 7, 4]|
| 3|[3, 0, 6]|
| 4|[1, 6, 7]|
+---+---------+
与其他转换相比,这实际上会提高性能,因为pyspark不必序列化udf。