如何有条件地用整数替换Pyspark数据框

时间:2018-11-28 17:51:44

标签: apache-spark dataframe

我正在尝试(在pyspark / spark内)。具体来说,数据框如下所示:

ID    response_variable    id_name
id_1   NULL                 "randomidDKHFD"
id_2   NULL                 NULL
id_3   NULL                 "randomid86438"

我希望能够转换数据帧,以便每当id_name具有非NULL条目时,response_variable就会变为1。因此,在此示例中:

ID    response_variable    in_data
id_1   1                 "randomidDKHFD"
id_2   NULL                NULL
id_3   1                 "randomid86438"

有人知道该怎么做吗?

1 个答案:

答案 0 :(得分:1)

您可以使用withColumnwhen来做到这一点。

Python:

yourDf.withColumn("response_variable", when(col("id_name").isNotNull(), lit(1)).otherwise(col("response_variable")))

斯卡拉:

yourDf.withColumn("response_variable", when(col("id_name").isNotNull, lit(1)).otherwise(col("response_variable")))