PySpark:具有多个输出的功能

Fed*_*ede 9 python apache-spark pyspark pyspark-sql

我正在尝试使用"链接时"功能.换句话说,我想获得两个以上的输出.

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

  df.withColumn("device_id", when(col("device")=="desktop",1)).otherwise(when(col("device")=="mobile",2)).otherwise(null))
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为我无法将元组放入"其他"功能.

Grr*_*Grr 21

你有没有尝试过:

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

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

  • 这些是链式操作-如果多个when()为true,是否为变量分配了第一个条件为True或最后一个条件? (2认同)
  • @Thomas如果多个连续的when()语句为true,则仅考虑第一个评估为true的when()。 (2认同)