我的目标是将 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 存在优化问题,因此这绝对不是正确的方法。但我不知道如何比较其他两种情况。一个答案绝对应该是进行实验并比较平均运行时间等等。但我想从理论上比较这些方法(和新方法)。
提前致谢...
最佳答案
您可以简单地创建一个列,在其中输入 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()
关于python - 将 PySpark DataFrame 列中的负值替换为零的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713478/