gpt4 book ai didi

apache-spark - 使用包含至少一个特定值的窗口过滤数据框

转载 作者:行者123 更新时间:2023-12-04 09:05:47 24 4
gpt4 key购买 nike

假设您有一个包含两列的 pyspark 数据框,idval .
您要过滤行,其中单个 id -window 至少有一个 val具有一定值的条目。
例如。如果我们想获取行,其中 id -window 至少有一个 5 val 中的值柱子:

# Input:

df = spark.createDataFrame(
[(1, '0'),
(1, '5'),
(2, '2'),
(2, '5'),
(2, '5'),
(3, '1'),
(3, '0'),],
['id', 'val']
)

# Desired output:

+---+----+
| id| val|
+---+----+
| 1| 0|
| 1| 5|
| 2| 2|
| 2| 5|
| 2| 5|
+---+----+
我想过以某种方式使用窗口函数吗?

最佳答案

使用 array_contains() 函数来自 Spark-2.4然后加入df只得到身份证 5 val 在他们。
Example:

from pyspark.sql.functions import *
from pyspark.sql.types import *

df1=df.groupBy("id").\
agg(array_contains(collect_set(col("val")).cast("array<int>"),5).alias("has_5")).\
filter(col("has_5")).\
drop('has_5')

df.join(df1,['id'],'inner').show()
#+---+---+
#| id|val|
#+---+---+
#| 1| 0|
#| 1| 5|
#| 2| 2|
#| 2| 5|
#| 2| 5|
#+---+---+
Another way Using Window function:
import sys
from pyspark.sql import *

w=Window.partitionBy("id").orderBy("val").rowsBetween(-sys.maxsize,sys.maxsize)

df.withColumn("has_5",array_contains(collect_set(col("val")).over(w).cast("array<int>"),5)).\
filter(col("has_5")).\
drop("has_5").\
show()
#+---+---+
#| id|val|
#+---+---+
#| 1| 0|
#| 1| 5|
#| 2| 2|
#| 2| 5|
#| 2| 5|
#+---+---+

关于apache-spark - 使用包含至少一个特定值的窗口过滤数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63451475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com