如何基于对Pyspark中另一列的表达式求值,有条件地替换一列中的值?

编程入门 行业动态 更新时间:2024-10-09 06:28:31
本文介绍了如何基于对Pyspark中另一列的表达式求值,有条件地替换一列中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 import numpy as np df = spark.createDataFrame( [(1, 1, None), (1, 2, float(5)), (1, 3, np.nan), (1, 4, None), (0, 5, float(10)), (1, 6, float('nan')), (0, 6, float('nan'))], ('session', "timestamp1", "id2"))

+-------+----------+----+ |session|timestamp1| id2| +-------+----------+----+ | 1| 1|null| | 1| 2| 5.0| | 1| 3| NaN| | 1| 4|null| | 0| 5|10.0| | 1| 6| NaN| | 0| 6| NaN| +-------+----------+----+

当session == 0时,如何将timestamp1列的值替换为999?

How to replace value of timestamp1 column with value 999 when session==0?

预期产量

Expected output

+-------+----------+----+ |session|timestamp1| id2| +-------+----------+----+ | 1| 1|null| | 1| 2| 5.0| | 1| 3| NaN| | 1| 4|null| | 0| 999|10.0| | 1| 6| NaN| | 0| 999| NaN| +-------+----------+----+

是否可以在PySpark中使用replace()做到这一点?

Is it possible to do it using replace() in PySpark?

推荐答案

您应该使用when(带有otherwise)功能:

You should be using the when (with otherwise) function:

from pyspark.sql.functions import when targetDf = df.withColumn("timestamp1", \ when(df["session"] == 0, 999).otherwise(df["timestamp1"]))

更多推荐

如何基于对Pyspark中另一列的表达式求值,有条件地替换一列中的值?

本文发布于:2023-11-30 07:42:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   有条件   求值   Pyspark

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!