Yue*_*Lyu 11 apache-spark apache-spark-sql pyspark spark-dataframe pyspark-sql
我有一个PySpark Dataframe,它有两列Id和rank,
+---+----+
| Id|Rank|
+---+----+
| a| 5|
| b| 7|
| c| 8|
| d| 1|
+---+----+
Run Code Online (Sandbox Code Playgroud)
对于每一行,如果Rank大于5,我希望用"other"替换Id.
如果我使用伪代码来解释:
For row in df:
if row.Rank>5:
then replace(row.Id,"other")
Run Code Online (Sandbox Code Playgroud)
结果应该是这样的,
+-----+----+
| Id|Rank|
+-----+----+
| a| 5|
|other| 7|
|other| 8|
| d| 1|
+-----+----+
Run Code Online (Sandbox Code Playgroud)
任何线索如何实现这一目标?谢谢!!!
要创建此Dataframe:
df = spark.createDataFrame([('a',5),('b',7),('c',8),('d',1)], ["Id","Rank"])
Run Code Online (Sandbox Code Playgroud)
Pus*_*hkr 24
你可以使用when和otherwise喜欢 -
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()
Run Code Online (Sandbox Code Playgroud)
这给出了输出 -
+-----+----+
| Id|Rank|
+-----+----+
| a| 5|
|other| 7|
|other| 8|
| d| 1|
+-----+----+
Run Code Online (Sandbox Code Playgroud)
从@Pushkr 解决方案开始,您不能只使用以下内容吗?
from pyspark.sql.functions import *
df.withColumn('Id',when(df.Rank <= 5,df.Id).otherwise('other')).show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21311 次 |
| 最近记录: |