【问题标题】:New column creation based on if and else condition using pyspark使用 pyspark 基于 if 和 else 条件创建新列
【发布时间】:2019-05-23 17:00:29
【问题描述】:

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

  • 如果 df1.colx 中存在 df2.colx 值。

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

cc002 = df2.withColumn('seg',F.when(df2.colx == df1.colx,"True").otherwise("FALSE"))
  • df1:
id  colx  coly
1   678   56789
2   900   67890
3   789   67854
  • df2
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


    【解决方案1】:

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

    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|
    +-----+----+-----+
    

    【讨论】:

    • 不幸的是,加入后我得到 0 条空值记录(真实计数为 0)
    【解决方案2】:

    您可以加入colx 并使用False 填充空值:

    result = (df2.join(df1.select(df1['colx'], F.lit(True).alias('seg')), 
                       on='colx', 
                       how='left')
                 .fillna(False, subset='seg'))
    
    result.show()
    

    输出:

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

    【讨论】:

    • @Tilo 哪个数据类型?
    • 在我的代码中“colx”是一个“标识符(ID)”并且是字符串类型。我尝试使用您提供的解决方案。但它给出了例外
    • @Tilo 不应该有所作为。什么例外?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2014-03-09
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多