Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用零替换PySpark DataFrame列中的负值的最有效方法是什么?_Python_Pyspark_Pyspark Sql_Pyspark Dataframes - Fatal编程技术网

Python 用零替换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 | +-

我的目标是用零替换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  |
+------+
基本上我可以这样做,如下所示:

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)进行比较