【发布时间】:2016-07-11 05:50:06
【问题描述】:
我有这个代码:
from pyspark import SparkContext
from pyspark.sql import SQLContext, Row
sc = SparkContext()
sqlContext = SQLContext(sc)
documents = sqlContext.createDataFrame([
Row(id=1, title=[Row(value=u'cars', max_dist=1000)]),
Row(id=2, title=[Row(value=u'horse bus',max_dist=50), Row(value=u'normal bus',max_dist=100)]),
Row(id=3, title=[Row(value=u'Airplane', max_dist=5000)]),
Row(id=4, title=[Row(value=u'Bicycles', max_dist=20),Row(value=u'Motorbikes', max_dist=80)]),
Row(id=5, title=[Row(value=u'Trams', max_dist=15)])])
documents.show(truncate=False)
#+---+----------------------------------+
#|id |title |
#+---+----------------------------------+
#|1 |[[1000,cars]] |
#|2 |[[50,horse bus], [100,normal bus]]|
#|3 |[[5000,Airplane]] |
#|4 |[[20,Bicycles], [80,Motorbikes]] |
#|5 |[[15,Trams]] |
#+---+----------------------------------+
我需要将所有复合行(例如 2 和 4)拆分为多行,同时保留“id”,以获得如下结果:
#+---+----------------------------------+
#|id |title |
#+---+----------------------------------+
#|1 |[1000,cars] |
#|2 |[50,horse bus] |
#|2 |[100,normal bus] |
#|3 |[5000,Airplane] |
#|4 |[20,Bicycles] |
#|4 |[80,Motorbikes] |
#|5 |[15,Trams] |
#+---+----------------------------------+
【问题讨论】:
-
我没有时间写出答案(对不起!),但这是我正在构建的想法:将 ID 放入“标题”类别中的每个元素中(比如让每个复合行包含
value、max_dist和id),然后执行flatMap。您将无法使用map,因为map期望输入和输出之间存在一对一的关系。如果以后有时间会充实一个答案! -
谢谢@Katya Handler,我会试试你的想法。如果我不能,我会通过评论请求你的帮助:-)
标签: python apache-spark dataframe pyspark apache-spark-sql