Cómo convertir un DataFrame a RDD normal en pyspark?
Necesito usar el
(rdd.)partitionBy(npartitions, custom_partitioner)
Método que no está disponible en el DataFrame. Todos los métodos DataFrame se refieren solo a los resultados de DataFrame. Entonces, ¿cómo crear un RDD a partir de los datos de DataFrame?
Nota: este es un cambio (en 1.3.0) de 1.2.0.
Actualizar de la respuesta de @ dpangmao: el método es .rdd. Estaba interesado en entender si (a) era público y (b) cuáles son las implicaciones de rendimiento.
Bien (a) es sí y (b) - bien se puede vea aquí que hay implicaciones perf significativas: un nuevo RDD debe ser creado invocando mapPartitions :
En dataframe.py (tenga en cuenta que el nombre del archivo también cambió (fue sql.py):
@property
def rdd(self):
"""
Return the content of the :class:`DataFrame` as an :class:`RDD`
of :class:`Row` s.
"""
if not hasattr(self, '_lazy_rdd'):
jrdd = self._jdf.javaToPython()
rdd = RDD(jrdd, self.sql_ctx._sc, BatchedSerializer(PickleSerializer()))
schema = self.schema
def applySchema(it):
cls = _create_cls(schema)
return itertools.imap(cls, it)
self._lazy_rdd = rdd.mapPartitions(applySchema)
return self._lazy_rdd
3 answers
La respuesta de@dapangmao funciona, pero no da el RDD normal de spark, devuelve un objeto Row. Si desea tener el formato RDD normal.
Prueba esto:
rdd = df.rdd.map(tuple)
O
rdd = df.rdd.map(list)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-21 03:54:00
Usa el método .rdd
así:
rdd = df.rdd
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-05 22:01:29
La respuesta dada por kennyut / Kistian funciona muy bien, pero para obtener una salida RDD exacta como cuando RDD consiste en una lista de atributos por ejemplo, [1,2,3,4] podemos usar el comando flatmap como se muestra a continuación,
rdd = df.rdd.flatMap(list)
or
rdd = df.rdd.flatmap(lambda x: list(x))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 18:09:28