如何根据基于Pyspark中另一列的表达式评估有条件地替换列中的值?

时间:2017-06-27 06:40:59

标签: apache-spark pyspark apache-spark-sql pyspark-sql

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时,如何用值999替换timestamp1列的值?

预期输出

+-------+----------+----+
|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()吗?

1 个答案:

答案 0 :(得分:28)

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

from pyspark.sql.functions import when

targetDf = df.withColumn("timestamp1", \
              when(df["session"] == 0, 999).otherwise(df["timestamp1"]))