Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose rows to columns in pyspark

How can I transpose a Dataframe table with only one column and multiple rows like:

1
2
3
5
6
7
...

to a dataframe with only one row and multiple columns like:

1,2,3,4,5,6,7,8,9,10,...
like image 730
Atuma Avatar asked Dec 04 '25 12:12

Atuma


1 Answers

Simply do a 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|
+---+---+---+---+---+---+---+---+---+---+
like image 58
Steven Avatar answered Dec 07 '25 02:12

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!