gpt4 book ai didi

apache-spark - PySpark:withColumn() 有两个条件和三个结果

转载 作者:行者123 更新时间:2023-12-03 09:15:30 29 4
gpt4 key购买 nike

我正在使用 Spark 和 PySpark。我正在尝试实现等效于以下伪代码的结果:

df = df.withColumn('new_column', 
IF fruit1 == fruit2 THEN 1, ELSE 0. IF fruit1 IS NULL OR fruit2 IS NULL 3.)

我正在尝试在 PySpark 中执行此操作,但我不确定语法。任何指针?我查看了 expr()但无法让它工作。

请注意 dfpyspark.sql.dataframe.DataFrame .

最佳答案

有几种有效的方法可以实现这一点。让我们从必需的导入开始:

from pyspark.sql.functions import col, expr, when

您可以使用 Hive IF expr 中的函数:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)

when + otherwise :
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)

最后你可以使用以下技巧:
from pyspark.sql.functions import coalesce, lit

new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))

使用示例数据:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])

您可以按如下方式使用它:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))

结果是:

+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+

关于apache-spark - PySpark:withColumn() 有两个条件和三个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40161879/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com