PySpark数据帧:如何用压缩代码过滤多个条件?

2024-09-28 16:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个列名列表,如果这些列的值大于零,我想对行进行筛选,我能做些类似的事情吗?在

columns = ['colA','colB','colC','colD','colE','colF']
new_df = df.filter(any([df[c]>0 for c in columns]))

这将返回:

ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions

我想我可以将这些列和过滤器只在一列上求和(因为我没有负数)。但如果我有求和技巧就行不通了。不管怎样,如果我必须在不同于求和的条件下过滤这些列,我怎么能做我想做的事情呢? 有什么想法吗?在


Tags: columnsindf列表newforanyfilter
1条回答
网友
1楼 · 发布于 2024-09-28 16:20:52

您可以改为使用or_运算符:

from operator import or_
from functools import reduce

newdf = df.where(reduce(or_, (df[c] > 0 for c in df.columns)))

编辑:更多pythonista解决方案:

^{pr2}$

编辑2:完整示例:

Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 2.1.0-SNAPSHOT
      /_/

Using Python version 3.5.1 (default, Dec  7 2015 11:16:01)
SparkSession available as 'spark'.

In [1]: from pyspark.sql.functions import lit

In [2]: %pas
%paste     %pastebin  

In [2]: %paste
def any_(*preds):
    cond = lit(False)
    for pred in preds:
        cond = cond | pred
    return cond

##   End pasted text  

In [3]: df = sc.parallelize([(1, 2, 3), (-1, -2, -3), (1, -1, 0)]).toDF()

In [4]: df.where(any_(*[df[c] > 0 for c in df.columns])).show()
# + -+ -+ -+
# | _1| _2| _3|
# + -+ -+ -+
# |  1|  2|  3|
# |  1| -1|  0|
# + -+ -+ -+

In [5]: df[any_(*[df[c] > 0 for c in df.columns])].show()
# + -+ -+ -+
# | _1| _2| _3|
# + -+ -+ -+
# |  1|  2|  3|
# |  1| -1|  0|
# + -+ -+ -+

In [6]: df.show()
# + -+ -+ -+
# | _1| _2| _3|
# + -+ -+ -+
# |  1|  2|  3|
# | -1| -2| -3|
# |  1| -1|  0|
# + -+ -+ -+

相关问题 更多 >