Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pyspark – Transpose

In Pyspark have dataset as below

+-----------+-----------+                                                       
|weekend_day|totals     |
+-----------+-----------+
| 2023-02-25|  401943676|
| 2023-03-11|  410220150|
+-----------+-----------+

and the expected output is

 -----------------------------------
|        | 2023-02-25 | 2023-03-11 |
| totals | 401943676  | 410220150  |

pivot is not providing the result. Please advice how it can be achieved?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please note I don’t want to use Pandas

Thank you

>Solution :

Not sure what do you mean of pivot is not providing the result?

df = spark.createDataFrame(
    [('2023-02-25', 401943676), ('2023-03-11', 410220150)],
    schema=['weekend_day', 'totals']
)
df.printSchema()
df.show(3, False)
+-----------+---------+
|weekend_day|totals   |
+-----------+---------+
|2023-02-25 |401943676|
|2023-03-11 |410220150|
+-----------+---------+

You can use groupBy and pivot to achieve the expected output:
from pyspark.sql import functions as func

df.groupBy(
    func.lit('total').alias('col_name')
).pivot(
    'weekend_day'
).agg(
    func.first('totals')
).show(
    10, False
)
+--------+----------+----------+
|col_name|2023-02-25|2023-03-11|
+--------+----------+----------+
|total   |401943676 |410220150 |
+--------+----------+----------+
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading