简体   繁体   English

根据列值的变化对pyspark数据帧进行分区

[英]Partition pyspark dataframe based on the change in column value

I have a dataframe in pyspark. 我在pyspark中有一个数据框。 Say the has some columns a,b,c... I want to group the data into groups as the value of column changes. 说有一些列a,b,c ...随着列的值更改,我想将数据分组。 Say

A  B
1  x
1  y
0  x
0  y
0  x
1  y
1  x
1  y

There will be 3 groups as (1x,1y),(0x,0y,0x),(1y,1x,1y) And corresponding row data 将有3组为(1x,1y),(0x,0y,0x),(1y,1x,1y)和相应的行数据

If I understand correctly you want to create a distinct group every time column A changes values. 如果我理解正确,那么您希望每次A列更改值时都创建一个不同的组。

First we'll create a monotonically increasing id to keep the row order as it is: 首先,我们将创建一个单调递增的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|
    +---+---+----------+

Now we'll use a window function to create a column that contains 1 every time column A changes: 现在,我们将使用窗口函数创建一个列,每次列A更改时该列包含1

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|
    +---+---+----------+-------+

Finally we'll use another window function to allocate different numbers to each group: 最后,我们将使用另一个窗口函数为每个组分配不同的数字:

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|
    +---+---+--------+

Now you can build you groups 现在您可以建立小组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM