使用正则表达式检查多个列中是否有任何大于零的列

Dus*_*sty 2 apache-spark apache-spark-sql pyspark

我需要在多列上应用when 函数。我想检查是否至少有一列的值大于 0。

这是我的解决方案:

df.withColumn("any value", F.when(
   (col("col1") > 0) |
   (col("col2") > 0) |
   (col("col3") > 0) |
   ...
   (col("colX") > 0)
   , "any greater than 0").otherwise(None))
Run Code Online (Sandbox Code Playgroud)

是否可以使用正则表达式执行相同的任务,这样我就不必编写所有列名称?

Oli*_*Oli 5

那么让我们创建示例数据:

 df = spark.createDataFrame(
    [(0, 0, 0, 0), (0, 0, 2, 0), (0, 0, 0, 0), (1, 0, 0, 0)],
    ['a', 'b', 'c', 'd']
)
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用map和reduce从列列表(例如数据帧的所有列)构建条件,如下所示:

cols = df.columns
from pyspark.sql import functions as F
condition = reduce(lambda a, b: a | b, map(lambda c: F.col(c) > 0, cols))
df.withColumn("any value", F.when(condition, "any greater than 0")).show()
Run Code Online (Sandbox Code Playgroud)

产生:

+---+---+---+---+------------------+
|  a|  b|  c|  d|         any value|
+---+---+---+---+------------------+
|  0|  0|  0|  0|              null|
|  0|  0|  2|  0|any greater than 0|
|  0|  0|  0|  0|              null|
|  1|  0|  0|  0|any greater than 0|
+---+---+---+---+------------------+
Run Code Online (Sandbox Code Playgroud)