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: Convert list to list of lists

In a pyspark dataframe, I have a column which has list values, for example: [1,2,3,4,5,6,7,8]

I would like to convert the above as [[1,2,3,4] , [5,6,7,8]] given 4 for every column value.

Please let me know, how can I achieve this.

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

Thanks for your help in advance.

>Solution :

You can use transform function as shown below:

df = spark.createDataFrame([([1, 2, 3, 4, 5, 6, 7, 8],)], ['values'])

df.selectExpr("transform(sequence(1, size(values), 4), v-> slice(values, v, 4)) as values")\
    .show(truncate=False)

+----------------------------+
|values                      |
+----------------------------+
|[[1, 2, 3, 4], [5, 6, 7, 8]]|
+----------------------------+
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