Jug*_*ngh 1 python dataframe pyspark spark-dataframe
我在pyspark中有一个数据框。说有一些列a,b,c ...随着列的值更改,我想将数据分组。说
A B
1 x
1 y
0 x
0 y
0 x
1 y
1 x
1 y
Run Code Online (Sandbox Code Playgroud)
将有3组作为(1x,1y),(0x,0y,0x),(1y,1x,1y)
和对应的行数据
如果我理解正确,那么您希望每次A列更改值时都创建一个不同的组。
首先,我们将创建一个单调递增的id,以保持行顺序不变:
import pyspark.sql.functions as psf
df = sc.parallelize([[1,'x'],[1,'y'],[0,'x'],[0,'y'],[0,'x'],[1,'y'],[1,'x'],[1,'y']])\
.toDF(['A', 'B'])\
.withColumn("rn", psf.monotonically_increasing_id())
df.show()
+---+---+----------+
| A| B| rn|
+---+---+----------+
| 1| x| 0|
| 1| y| 1|
| 0| x| 2|
| 0| y| 3|
| 0| x|8589934592|
| 1| y|8589934593|
| 1| x|8589934594|
| 1| y|8589934595|
+---+---+----------+
Run Code Online (Sandbox Code Playgroud)
现在,我们将使用窗口函数创建一个列,该列包含1列A每次更改的时间:
from pyspark.sql import Window
w = Window.orderBy('rn')
df = df.withColumn("changed", (df.A != psf.lag('A', 1, 0).over(w)).cast('int'))
+---+---+----------+-------+
| A| B| rn|changed|
+---+---+----------+-------+
| 1| x| 0| 1|
| 1| y| 1| 0|
| 0| x| 2| 1|
| 0| y| 3| 0|
| 0| x|8589934592| 0|
| 1| y|8589934593| 1|
| 1| x|8589934594| 0|
| 1| y|8589934595| 0|
+---+---+----------+-------+
Run Code Online (Sandbox Code Playgroud)
最后,我们将使用另一个窗口函数为每个组分配不同的数字:
df = df.withColumn("group_id", psf.sum("changed").over(w)).drop("rn").drop("changed")
+---+---+--------+
| A| B|group_id|
+---+---+--------+
| 1| x| 1|
| 1| y| 1|
| 0| x| 2|
| 0| y| 2|
| 0| x| 2|
| 1| y| 3|
| 1| x| 3|
| 1| y| 3|
+---+---+--------+
Run Code Online (Sandbox Code Playgroud)
现在您可以建立小组