【问题标题】:PySpark: when function with multiple outputs [duplicate]PySpark:当具有多个输出的功能时[重复]
【发布时间】:2017-07-21 02:16:08
【问题描述】:

我正在尝试使用“链接时”功能。 换句话说,我想得到两个以上的输出。

我尝试在 Excel 中使用与连接 IF 函数相同的逻辑:

  df.withColumn("device_id", when(col("device")=="desktop",1)).otherwise(when(col("device")=="mobile",2)).otherwise(null))

但这不起作用,因为我无法将元组放入“否则”函数中。

【问题讨论】:

    标签: python apache-spark pyspark pyspark-sql


    【解决方案1】:

    你试过了吗:

    from pyspark.sql import functions as F
    df.withColumn('device_id', F.when(col('device')=='desktop', 1).when(col('device')=='mobile', 2).otherwise(None))
    

    请注意,在链接 when 函数时,您不需要将连续调用包装在 otherwise 函数中。

    【讨论】:

    • 有效!非常感谢!!
    • when 链接组合超级有用!谢谢!
    • 这些是链式操作 - 如果多个 when() 为真,变量是被分配第一个条件为真还是最后一个条件?
    • @Thomas 如果多个连续的 when() 语句为真,则只考虑第一个 when() 评估为真。
    猜你喜欢
    • 2012-01-03
    • 2017-09-10
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多