【问题标题】:Pyspark : How to select the dataframe with conditionPyspark:如何选择有条件的数据框
【发布时间】:2021-11-23 21:13:01
【问题描述】:
我有这个数据框,我想浏览数组,当条件为1时,我停下来取最大值。例如,我取 max(16,8)= 8 ;最大值(6,10,9,8)=10。
| Identifiant |
Value |
Condition |
| ID1 |
16 |
1 |
| ID2 |
8 |
1 |
| ID3 |
4 |
0 |
| ID4 |
5 |
0 |
| ID5 |
6 |
1 |
| ID6 |
10 |
1 |
| ID7 |
9 |
1 |
| ID8 |
8 |
1 |
| ID9 |
9 |
0 |
| ID10 |
11 |
0 |
| ID11 |
6 |
1 |
| ID12 |
8 |
1 |
| ID13 |
10 |
0 |
| ID13 |
12 |
1 |
| ID14 |
15 |
0 |
| ID15 |
14 |
1 |
| ID16 |
8 |
1 |
| ID17 |
9 |
1 |
我们得到这张表:
| Identifiant |
Value |
|
| ID1 |
16 |
max(16,8) |
| ID6 |
10 |
max(6,10,9,8) |
| ID12 |
8 |
max(6,8) |
| ID13 |
12 |
max(12) |
| ID15 |
14 |
max(14,8,9) |
【问题讨论】:
标签:
arrays
dataframe
pyspark
【解决方案1】:
您可以为此创建单独的窗口。首先创建一个窗口来计算分配每个组的辅助列,即 1,1 得到 1,然后 0,0 得到 2,然后 1,1,1 得到 3,依此类推。一旦我们有了这个,我们就可以使用 Condition 列过滤掉零,并在获得降序排名以获得每个组的最大值后,获取帮助列的每个分区的最大值:
from pyspark.sql import functions as F, Window as W
w = W.orderBy("Identifiant")
w1 = w.rangeBetween(W.unboundedPreceding,0)
w2 = W.partitionBy("Helper").orderBy(F.desc("Value"))
c = (F.col("Condition")!=F.lag("Condition").over(w)).cast("int")
out = (df.withColumn("Helper",c).fillna({"Helper":0})
.withColumn("Helper",F.sum("Helper").over(w1)).filter("Condition!=0")
.withColumn("Rnk",F.dense_rank().over(w2)).filter("Rnk==1")
.drop("Helper","Rnk","Condition")
)
out.show()
+-----------+-----+
|Identifiant|Value|
+-----------+-----+
| ID1| 16|
| ID6| 10|
| ID12| 8|
| ID13| 12|
| ID15| 14|
+-----------+-----+