Reformar / pivotar datos en Spark RDD y / o Spark DataFrames

Tengo algunos datos en el siguiente formato (RDD o Spark DataFrame):

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

 rdd = sc.parallelize([('X01',41,'US',3),
                       ('X01',41,'UK',1),
                       ('X01',41,'CA',2),
                       ('X02',72,'US',4),
                       ('X02',72,'UK',6),
                       ('X02',72,'CA',7),
                       ('X02',72,'XX',8)])

# convert to a Spark DataFrame                    
schema = StructType([StructField('ID', StringType(), True),
                     StructField('Age', IntegerType(), True),
                     StructField('Country', StringType(), True),
                     StructField('Score', IntegerType(), True)])

df = sqlContext.createDataFrame(rdd, schema)

Lo que me gustaría hacer es 'remodelar' los datos, convertir ciertas filas en el país (específicamente en EE. UU., Reino Unido y CA) en columnas:

ID    Age  US  UK  CA  
'X01'  41  3   1   2  
'X02'  72  4   6   7   

Esencialmente, necesito algo en la línea de Pythonpivot Flujo de trabajo:

categories = ['US', 'UK', 'CA']
new_df = df[df['Country'].isin(categories)].pivot(index = 'ID', 
                                                  columns = 'Country',
                                                  values = 'Score')

Mi conjunto de datos es bastante grande, así que realmente no puedocollect() e ingiere los datos en la memoria para hacer la remodelación en Python. ¿Hay alguna manera de convertir Python.pivot() en una función invocable al mapear un RDD o un Spark DataFrame? ¡Cualquier ayuda sería apreciada!

Respuestas a la pregunta(6)

Su respuesta a la pregunta