问题描述
customer id|trigger_id
=======================
1 |1101
2 |1102
3 |1101
4 |1102
现在想以递增顺序将触发器的每个重复值排名为
customer id|trigger_id|rank
===========================
1 |1101 |1
2 |1102 |1
3 |1101 |2
4 |1102 |2
之后有两个不同的数据帧,一个具有所有偶数记录,而另一个具有所有奇数记录。
对不起,格式错误。
谢谢。
解决方法
使用window rank()
功能。
Example:
df.show()
#+-----------+----------+
#|customer_id|trigger_id|
#+-----------+----------+
#| 1| 1101|
#| 2| 1102|
#| 3| 1101|
#| 4| 1102|
#+-----------+----------+
from pyspark.sql.functions import *
from pyspark.sql import *
w=Window.partitionBy("trigger_id").orderBy("customer_id")
#using dense_rank()
df.withColumn("rank",rank().over(w)).show()
#+-----------+----------+----+
#|customer_id|trigger_id|rank|
#+-----------+----------+----+
#| 2| 1102| 1|
#| 4| 1102| 2|
#| 1| 1101| 1|
#| 3| 1101| 2|
#+-----------+----------+----+
对于唯一值,请使用 row_number()
:
df.withColumn("rank",row_number().over(w)).orderBy("customer_id").show()
df.withColumn("rank",dense_rank().over(w)).orderBy("customer_id").show()
#+-----------+----------+----+
#|customer_id|trigger_id|rank|
#+-----------+----------+----+
#| 1| 1101| 1|
#| 2| 1102| 1|
#| 3| 1101| 2|
#| 4| 1102| 2|
#+-----------+----------+----+