首页 > 解决方案 > 在 PySpark 中满足 when 子句时的多个操作

问题描述

pyspark中,我知道该when子句可以有多个条件来产生单个输出,如下所示:

df.withColumn(
  'Output', 
  when(
    (condition1==True) & (condition2==True), 
    do_something)
  .otherwise(do_something_else)
)

但是当一个条件满足时,是否可以执行多个输出?像这样:

df.when(
    condition1==True, withColumn('This', lit("yes")) 
    & withColumn('That', lit("also yes")))
  .otherwise(
    withColumn('This', lit("no")) 
    & withColumn('That', lit("also no"))
)

标签: pysparkapache-spark-sql

解决方案


您可以通过structwhen/otherwise子句中创建 a 来做到这一点。您可以name and create as many fields inside your struct将它们展开,colname.*如下所示。

df.show() #sample dataframe
#+-----+------+
#|Sales|Region|
#+-----+------+
#| 5000|    US|
#| 2500|    IN|
#| 4500|    AU|
#| 4500|    NZ|
#+-----+------+

from pyspark.sql import functions as F

df.withColumn("col", F.when(F.col("Region")=='US',\
                            F.struct(F.lit("yes").alias("This"),F.lit("also yes").alias("That")))\
                      .otherwise(F.struct(F.lit("no").alias("This"),F.lit("also no").alias("That"))))\
                      .select(*df.columns,"col.*")\
                      .show()

#+-----+------+----+--------+
#|Sales|Region|This|    That|
#+-----+------+----+--------+
#| 5000|    US| yes|also yes|
#| 2500|    IN|  no| also no|
#| 4500|    AU|  no| also no|
#| 4500|    NZ|  no| also no|
#+-----+------+----+--------+

推荐阅读