apache-spark - 使用正则表达式检查大于零的任何列的多个列
问题描述
我需要在多列上应用 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))
是否可以使用正则表达式执行相同的任务,因此我不必编写所有列名?
解决方案
因此,让我们创建示例数据:
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|
+---+---+---+---+------------------+
推荐阅读
- reactjs - 反应引导 | 我自己的示例与文档看起来不同
- google-sheets - 仅将复杂的 arrayformula() 应用于数据集中具有特定值的行
- c# - TcpClient NetworkStream DataAvailable False,但不是
- javascript - 进行添加到列表的输入
- python - 在原始方法调用之后提取方法并插入调用
- linux - 如何在 Airflow 中构建和上传 Docker 镜像?
- tcl - 调用“expect eof”时,预期脚本因“spawn id not open”而失败
- flutter - Flutter ObjectBox - 如何进行单元测试?
- outlook - 如果主题相同,Outlook 规则不会根据类别发送电子邮件
- reactjs - 使用 TypeScript 在 React 组件上强制执行属性