PySpark:将DataFrame拆分为多个DataFrame而不使用循环

时间:2017-05-09 13:18:03

标签: python apache-spark pyspark spark-dataframe

您好我有一个DataFrame -

ID       X        Y

1      1234      284

1      1396      179

2      8620      178

3      1620      191

3      8820      828

我希望根据ID将此DataFrame拆分为多个DataFrame。因此,对于此示例,将有3个DataFrame。实现它的一种方法是在循环中运行过滤器操作。但是,我想知道是否可以以更有效的方式完成。

1 个答案:

答案 0 :(得分:2)

#initialize spark dataframe
df = sc.parallelize([ (1,1234,282),(1,1396,179),(2,8620,178),(3,1620,191),(3,8820,828) ] ).toDF(["ID","X","Y"])

#get the list of unique ID values ; there's probably a better way to do this, but this was quick and easy
listids = [x.asDict().values()[0] for x in df.select("ID").distinct().collect()]
#create list of dataframes by IDs
dfArray = [df.where(df.ID == x) for x in listids]

dfArray[0].show()
+---+----+---+
| ID|   X|  Y|
+---+----+---+
|  1|1234|282|
|  1|1396|179|
+---+----+---+
dfArray[1].show()
+---+----+---+
| ID|   X|  Y|
+---+----+---+
|  2|8620|178|
+---+----+---+

dfArray[2].show()
+---+----+---+
| ID|   X|  Y|
+---+----+---+
|  3|1620|191|
|  3|8820|828|
+---+----+---+