apache-spark - Spark:在每个组中过滤
问题描述
我有一个像
+------+-------------------+------+
|group | time| label|
+------+-------------------+------+
| a|2020-01-01 10:49:00|first |
| a|2020-01-01 10:51:00|second|
| a|2020-01-01 12:49:00|first |
| b|2020-01-01 12:44:00|second|
| b|2020-01-01 12:46:00|first |
| c|2020-01-01 12:46:00|third |
+------+-------------------+------+
我想删除所有行,对于每个组,标签first
比 labelsecond
或third
. 例如,在 group中,应该删除a
带有first
and的行,因为有一个带有标签的旧行。2020-01-01 12:49:00
second
所需的输出将是:
+------+-------------------+------+
|group | time| label|
+------+-------------------+------+
| a|2020-01-01 10:49:00|first |
| a|2020-01-01 10:51:00|second|
| b|2020-01-01 12:44:00|second|
| c|2020-01-01 12:46:00|third |
+------+-------------------+------+
具有分区依据的窗口函数group
将在每个组内过滤,但是如何在标签上实现过滤器?
解决方案
您可以使用不是“第一”的标签获取上一次,并使用该列进行过滤:
import org.apache.spark.sql.expressions.Window
val df2 = df.withColumn(
"non_first_time",
last(
when(col("label") =!= "first", col("time")),
true
).over(
Window.partitionBy("group").orderBy("time")
)
).filter("""
label != 'first' or
(label = 'first' and (non_first_time > time or non_first_time is null))
""").drop("non_first_time")
df2.show
+-----+-------------------+------+
|group| time| label|
+-----+-------------------+------+
| c|2020-01-01 12:46:00| third|
| b|2020-01-01 12:44:00|second|
| a|2020-01-01 10:49:00| first|
| a|2020-01-01 10:51:00|second|
+-----+-------------------+------+
推荐阅读
- c# - EntityFrameWork Core 5.0 尝试从不存在的原始查询中删除 dbset
- python - 用python绘制(x,y)点对点连接
- python-3.x - 绘制形状代替使用图像
- python - 仅使用 itertools 重复迭代中的每个元素(可以是无限的)
- python - 尝试访问键时,字典位于其他函数错误 [Python]
- c - 正确读取先前条目后,文件 * 正在从输入文本文件中将零读入“双”变量
- html - 即使溢出设置为滚动,元素也被推到页面上方
- r - ggplot中的错误我无法生成条形图
- javascript - Javascript重启功能
- python - 有没有办法将函数作为参数,但在给出返回值之前以某种方式修改函数调用?