我必须对pyspark中的where
函数中的条件列表应用逻辑运算符or
。正如在pyspark中or
的运算符是|
,它不能使用Python中的any()
函数。有谁能提出解决这个问题的建议吗
下面是一个简单的例子:
# List of conditions
spark_conditions = [cond1, cond2, ..., cond100]
# Apply somehow the '|' operator on `spark_conditions`
# spark_conditions would look like -> [cond1 | cond2 | .... | cond100]
df.select(columns).where(spark_conditions)
谢谢你的帮助,谢谢
2e0byo的answer非常正确。我正在添加另一种方法,如何在pyspark中实现这一点
如果我们的条件是SQL条件表达式的字符串(如col_1=='ABC101'),那么我们可以组合所有这些字符串,并将组合后的字符串作为条件提供给
where()
(或filter()
)" or ".join(conditions)
通过使用or
作为分隔符/连接符/组合器连接conditions
中存在的所有字符串来创建字符串。这里,combined_or_condition
变成了id == 1 or id == 4 or id == 6
我认为这实际上是一个熊猫问题,因为
spark.sql.DataFrame
似乎至少表现得像熊猫数据帧。但我不知道斯帕克。在任何情况下,你的“火花条件”实际上是(我认为)布尔级数。我确信有一些方法可以正确地对pandas中的布尔级数求和,但您也可以也将其简化为:其工作原理如下:
reduce()
获取过滤器中的前两项内容并在其上运行lambda x, y: x | y
。然后它获取的的输出,并将其作为x
传递到lambda x, y: x | y
,将filters
中的第三个条目作为y
传递。它一直在走,直到没有什么东西可以带走因此,净效应是沿着一个可数累积应用一个函数。在这种情况下,函数只返回其输入的
|
,因此它完全执行您手动执行的操作,但如下所示:我怀疑有一种更简单的方法可以做到这一点,但reduce有时是值得的Guido doesn't like it though
相关问题 更多 >
编程相关推荐