PySpark: modify column values when another column value satisfies a condition

孤人 提交于 2019-11-27 03:22:06

问题


I have a PySpark Dataframe that has two columns Id and rank,

+---+----+
| Id|Rank|
+---+----+
|  a|   5|
|  b|   7|
|  c|   8|
|  d|   1|
+---+----+

For each row, I'm looking to replace Id with "other" if Rank is larger 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,

+-----+----+
|   Id|Rank|
+-----+----+
|    a|   5|
|other|   7|
|other|   8|
|    d|   1|
+-----+----+

Any clue how to achieve this? Thanks!!!


To create this Dataframe:

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

回答1:


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 output as -

+-----+----+
|   Id|Rank|
+-----+----+
|    a|   5|
|other|   7|
|other|   8|
|    d|   1|
+-----+----+


来源:https://stackoverflow.com/questions/43988801/pyspark-modify-column-values-when-another-column-value-satisfies-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!