将行转置为pyspark中的列

时间:2019-10-08 12:57:23

标签: python pyspark pyspark-sql pyspark-dataframes

如何转置只有一列和多行的Dataframe表,如:

1
2
3
5
6
7
...

到只有一行和多列的数据框,例如:

1,2,3,4,5,6,7,8,9,10,...

1 个答案:

答案 0 :(得分:1)

只需执行pivot

df = spark.range(10)

df.show()
+---+                                                                           
| id|
+---+
|  0|
|  1|
|  2|
|  3|
|  4|
|  5|
|  6|
|  7|
|  8|
|  9|
+---+


df.groupBy().pivot("id").count().show()                                                                            
+---+---+---+---+---+---+---+---+---+---+                                       
|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9|
+---+---+---+---+---+---+---+---+---+---+
|  1|  1|  1|  1|  1|  1|  1|  1|  1|  1|
+---+---+---+---+---+---+---+---+---+---+

df.groupBy().pivot("id").agg(F.first(F.col("id"))).show()                                                          
+---+---+---+---+---+---+---+---+---+---+                                       
|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9|
+---+---+---+---+---+---+---+---+---+---+
|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9|
+---+---+---+---+---+---+---+---+---+---+