PySpark: change column values ββwhen another column value meets a condition
I have a PySpark framework that has two columns Id and rank,
+---+----+
| Id|Rank|
+---+----+
| a| 5|
| b| 7|
| c| 8|
| d| 1|
+---+----+
For each line, I am looking to replace the Id with "other" if the Rank is greater than 5.
If I use pseudocode to explain:
For row in df:
if row.Rank>5:
then replace(row.Id,"other")
The result should look like this:
+-----+----+
| Id|Rank|
+-----+----+
| a| 5|
|other| 7|
|other| 8|
| d| 1|
+-----+----+
Any hint how to achieve this? Thank!!!
To create this Dataframe:
df = spark.createDataFrame([('a',5),('b',7),('c',8),('d',1)], ["Id","Rank"])
+3
source to share
1 answer
You can use when
and otherwise
like -
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()
this gives the result as -
+-----+----+
| Id|Rank|
+-----+----+
| a| 5|
|other| 7|
|other| 8|
| d| 1|
+-----+----+
+5
source to share