本文介绍了PySpark:当另一个列值满足条件时修改列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个PySpark数据框,其中有两列ID和等级,
I have a PySpark Dataframe that has two columns Id and rank,
+---+----+
| Id|Rank|
+---+----+
| a| 5|
| b| 7|
| c| 8|
| d| 1|
+---+----+
对于每一行,如果排名大于5,我希望将ID替换为其他".
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")
结果应类似于
+-----+----+
| 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"])
推荐答案
您可以像<
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()
这将输出显示为-
+-----+----+
| Id|Rank|
+-----+----+
| a| 5|
|other| 7|
|other| 8|
| d| 1|
+-----+----+
这篇关于PySpark:当另一个列值满足条件时修改列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!