Apache spark PySpark:当另一列值满足条件时修改列值

Apache spark PySpark:当另一列值满足条件时修改列值,apache-spark,pyspark,apache-spark-sql,Apache Spark,Pyspark,Apache Spark Sql,我有一个PySpark数据框,有两列: +---+----+ | Id|Rank| +---+----+ | a| 5| | b| 7| | c| 8| | d| 1| +---+----+ 对于每一行,如果Rankcolumn大于5,我希望将Id列替换为“other” 如果我使用伪代码来解释: For row in df: if row.Rank > 5: then replace(row.Id, "other") 结果应该如

我有一个PySpark数据框,有两列:

+---+----+
| Id|Rank|
+---+----+
|  a|   5|
|  b|   7|
|  c|   8|
|  d|   1|
+---+----+
对于每一行,如果
Rank
column大于5,我希望将
Id
列替换为“other”

如果我使用伪代码来解释:

For row in df:
  if row.Rank > 5:
     then replace(row.Id, "other")
结果应该如下所示:

+-----+----+
|   Id|Rank|
+-----+----+
|    a|   5|
|other|   7|
|other|   8|
|    d|   1|
+-----+----+
你知道如何做到这一点吗?谢谢


要创建此数据帧,请执行以下操作:

df = spark.createDataFrame([('a', 5), ('b', 7), ('c', 8), ('d', 1)], ['Id', 'Rank'])

当时可以使用
,否则可以使用
,如-

from pyspark.sql.functions import *

df\
.withColumn('Id_New',when(df.Rank <= 5,df.Id).otherwise('other'))\
.drop(df.Id)\
.select(col('Id_New').alias('Id'),col('Rank'))\
.show()

从@Pushkr解决方案开始,您就不能使用以下内容吗

from pyspark.sql.functions import *

df.withColumn('Id',when(df.Rank <= 5,df.Id).otherwise('other')).show()
从pyspark.sql.functions导入*

df.withColumn('Id',when(df.Rank nice one@Pushkr!@titiro89)您的是一个解释RDD和map用法的清晰解决方案!谢谢!它在这个示例上工作,但在我的实际数据集上,“a=df.RDD”操作产生了一系列任务并最终失败。不确定从df更改为RDD是否昂贵。
from pyspark.sql.functions import *

df.withColumn('Id',when(df.Rank <= 5,df.Id).otherwise('other')).show()