【问题标题】:What is the most efficient way of replacing negative values in PySpark DataFrame column with zero?用零替换 PySpark DataFrame 列中的负值的最有效方法是什么?
【发布时间】:2019-11-06 00:35:09
【问题描述】:

我的目标是用零替换 PySpark.DataFrame 列中的所有负元素。

输入数据

+------+
| col1 |
+------+
|  -2  |
|   1  |
|   3  |
|   0  |
|   2  |
|  -7  |
|  -14 |
|   3  |
+------+

所需的输出数据

+------+
| col1 |
+------+
|   0  |
|   1  |
|   3  |
|   0  |
|   2  |
|   0  |
|   0  |
|   3  |
+------+

基本上我可以这样做:

df = df.withColumn('col1', F.when(F.col('col1') < 0, 0).otherwise(F.col('col1'))

或者udf可以定义为

import pyspark.sql.functions as F
smooth = F.udf(lambda x: x if x > 0 else 0, IntegerType())
df = df.withColumn('col1', smooth(F.col('col1')))

df = df.withColumn('col1', (F.col('col1') + F.abs('col1')) / 2)

df = df.withColumn('col1', F.greatest(F.col('col1'), F.lit(0))

我的问题是,哪一种是最有效的方法? Udf 有优化问题,所以绝对不是这样做的正确方法。但我不知道如何比较其他两种情况。一个答案应该是绝对做实验并比较平均运行时间等等。但我想从理论上比较这些方法(和新方法)。

提前谢谢...

【问题讨论】:

标签: python pyspark pyspark-sql pyspark-dataframes


【解决方案1】:

您可以简单地在您说if x > 0: x else 0 的地方创建一个列。这将是最好的方法。

理论上,这个问题已经解决了:Spark functions vs UDF performance?

import pyspark.sql.functions as F

df = df.withColumn("only_positive", F.when(F.col("col1") > 0, F.col("col1")).otherwise(0))

您可以覆盖原始数据帧中的col1,如果您将其传递给withColumn()

【讨论】:

  • 我已经在我的问题中给出了这个答案,并且 udf 比较是直截了当的。但问题实际上是如何将您提到的与 df = df.withColumn('col1', (F.col('col1') + F.abs('col1')) / 2) 进行比较
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2020-10-23
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 2012-07-01
相关资源
最近更新 更多