首页 > 解决方案 > 使用正则表达式检查大于零的任何列的多个列

问题描述

我需要在多列上应用 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))

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

标签: apache-sparkpysparkapache-spark-sql

解决方案


因此,让我们创建示例数据:

 df = spark.createDataFrame(
    [(0, 0, 0, 0), (0, 0, 2, 0), (0, 0, 0, 0), (1, 0, 0, 0)],
    ['a', 'b', 'c', 'd']
)

然后,您可以使用 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()

产生:

+---+---+---+---+------------------+
|  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|
+---+---+---+---+------------------+

推荐阅读