首页 > 解决方案 > 使用 pyspark 基于 if 和 else 条件创建新列

问题描述

我有 2 个 spark 数据框,我想根据以下条件将名为“seg”的新列添加到数据框 df2

我在 pyspark 中尝试了以下操作,但它抛出异常。

cc002 = df2.withColumn('seg',F.when(df2.colx == df1.colx,"True").otherwise("FALSE"))
id  colx  coly
1   678   56789
2   900   67890
3   789   67854
Name   colx
seema  900
yash   678
deep   800
harsh  900
Name  colx   seg
seema 900    True
harsh 900    True
yash  678    True
deep  800    False

请帮助我更正给定的 pyspark 代码或提出更好的方法。

标签: pyspark

解决方案


如果我正确理解你的问题你想要做的是这个

res = df2.join(
    df1,
    on="colx",
    how = "left"
).select(
    "Name",
    "colx"
).withColumn(
    "seg",
    F.when(F.col(colx).isNull(),F.lit(True)).otherwise(F.lit(False))
)

让我知道这是否是您想要的解决方案。

我很糟糕,我确实匆忙写了错误的代码,下面是更正的代码

import pyspark.sql.functions as F

df1 = sqlContext.createDataFrame([[1,678,56789],[2,900,67890],[3,789,67854]],['id', 'colx', 'coly'])

df2 = sqlContext.createDataFrame([["seema",900],["yash",678],["deep",800],["harsh",900]],['Name', 'colx'])

res = df2.join(
    df1.withColumn(
        "check",
        F.lit(1)
    ),
    on="colx",
    how = "left"
).withColumn(
    "seg",
    F.when(F.col("check").isNotNull(),F.lit(True)).otherwise(F.lit(False))
).select(
    "Name",
    "colx",
    "seg"
)

res.show()

+-----+----+-----+
| Name|colx|  seg|
+-----+----+-----+
| yash| 678| true|
|seema| 900| true|
|harsh| 900| true|
| deep| 800|false|
+-----+----+-----+

推荐阅读