Python 用零替换PySpark DataFrame列中的负值的最有效方法是什么?
我的目标是用零替换PySpark.DataFrame列中的所有负元素 输入数据Python 用零替换PySpark DataFrame列中的负值的最有效方法是什么?,python,pyspark,pyspark-sql,pyspark-dataframes,Python,Pyspark,Pyspark Sql,Pyspark Dataframes,我的目标是用零替换PySpark.DataFrame列中的所有负元素 输入数据 +------+ | col1 | +------+ | -2 | | 1 | | 3 | | 0 | | 2 | | -7 | | -14 | | 3 | +------+ +------+ | col1 | +------+ | 0 | | 1 | | 3 | | 0 | | 2 | | 0 | | 0 | | 3 | +-
+------+
| col1 |
+------+
| -2 |
| 1 |
| 3 |
| 0 |
| 2 |
| -7 |
| -14 |
| 3 |
+------+
+------+
| col1 |
+------+
| 0 |
| 1 |
| 3 |
| 0 |
| 2 |
| 0 |
| 0 |
| 3 |
+------+
所需的输出数据
+------+
| 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)。否则(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.magest(F.col('col1'),F.lit(0))
我的问题是,哪种方法最有效?Udf有优化问题,所以绝对不是正确的方法。但我不知道如何比较其他两种情况。一个答案应该是绝对进行实验和比较平均运行时间等。但我想比较这些方法aches(和新方法)在理论上
提前感谢…您只需在列中写下,
如果x>0:x否则0
。这将是最好的方法
理论上,这个问题已经得到了解决:
您可以覆盖原始数据帧中的
col1
,如果您将其传递给withColumn()
您可以简单地创建一个列,其中您可以说,if x>0:x else 0
。这将是最好的方法
理论上,这个问题已经得到了解决:
如果将原始数据帧中的
col1
传递给withColumn()
spark.sql(“'select if(col1<0,0,col1)作为col1'”),则可以覆盖该数据帧中的在sql查询中的F.when和if条件之间?可能与如下所示的重复:,不要使用udf
代替简单的spark函数。spark.sql(''选择if(col1<0,0,col1)作为col1'')
有什么区别(在复杂性方面)在sql查询中的F.when和if条件之间?和的可能重复项如下:,不要使用udf
来代替简单的spark函数。我在问题中已经给出了答案,udf比较有点直截了当。但问题实际上是如何将您提到的一个与df=df.withColumn('col1')进行比较,(F.col('col1')+F.abs('col1'))/2)我在我的问题中已经给出了这个答案,udf比较有点直截了当。但问题实际上是如何将你提到的一个与df=df.withColumn('col1'),(F.col('col1')+F.abs('col1')/2)进行比较