Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Pyspark Dataframe column from array to new columns

I've a Pyspark Dataframe with this structure:

root
 |-- Id: string (nullable = true)
 |-- Q: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- pr: string (nullable = true)
 |    |    |-- qt: double (nullable = true)

Something similar to:

 +----+--------------------- ... --+
 | Id |           Q                |
 +----+---------------------- ... -+
 | 001| [ [pr1,1.9], [pr3,2.0]...] |
 | 002| [ [pr2,1.0], [pr9,3.9]...] |
 | 003| [ [pr2,9.0], ...         ] |
  ...

I wold like to convert Q array into columns (name pr value qt). Also I would like to avoid duplicated columns by merging (add) same columns.

 +----+-----+-----+------+ ... ----+
 | Id | pr1 | pr2 | pr3  | ... prn |
 +----+-----+-----+------+ ... ----+
 | 001| 1.9 | 0.0 | 2.0  | ...     |
 | 002| 0.0 | 1.0 | 0    | ...     |
 | 003| 0.0 | 9.0 | ...  | ...     |
  ...

How can I perform this transformation?. Thakyou in advance!!. Julián.

like image 350
Julián Gómez Avatar asked Dec 18 '17 18:12

Julián Gómez


1 Answers

You can do this with a combination of explode and pivot:

import pyspark.sql.functions as F

# explode to get "long" format
df=df.withColumn('exploded', F.explode('Q'))

# get the name and the name in separate columns
df=df.withColumn('name', F.col('exploded').getItem(0))
df=df.withColumn('value', F.col('exploded').getItem(1))

# now pivot
df.groupby('Id').pivot('name').agg(F.max('value')).na.fill(0)
like image 146
ags29 Avatar answered Oct 06 '22 15:10

ags29