gpt4 book ai didi

python - 在 Pyspark 中过滤具有空数组的列

转载 作者:行者123 更新时间:2023-12-04 02:28:39 25 4
gpt4 key购买 nike

我有一个包含大量重复值的 DataFrame。它的聚合的、不同的计数如下所示

> df.groupby('fruits').count().sort(F.desc('count')).show()


| fruits | count |
| ----------- | ----------- |
| [Apples] | 123 |
| [] | 344 |
| [Apples, plum]| 444 |

我的目标是过滤值为 [Apples][] 的所有行。

令人惊讶的是,下面的代码适用于非空数组,但对于空数组则不行

import pyspark.sql.types as T

is_apples = F.udf(lambda arr: arr == ['Apples'], T.BooleanType())
df.filter(is_apples(df.fruits).count() # WORKS! shows 123 correctly.

is_empty = F.udf(lambda arr: arr == [], T.BooleanType())
df.filter(is_empty(df.fruits).count() # Doesn't work! Should show 344 but shows zero.

知道我做错了什么吗?

最佳答案

它可能是一个包含空字符串的数组:

is_empty = F.udf(lambda arr: arr == [''], T.BooleanType())

或者它可能是一个空数组:

is_empty = F.udf(lambda arr: arr == [None], T.BooleanType())

要一次检查所有这些,您可以使用:

is_empty = F.udf(lambda arr: arr in [[], [''], [None]], T.BooleanType())

但实际上您不需要为此使用 UDF,例如你可以这样做:

df.filter("fruits = array() or fruits = array('') or fruits = array(null)")

关于python - 在 Pyspark 中过滤具有空数组的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65662265/

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