pyspark - 在 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"))
)
解决方案
您可以通过struct
在when/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|
#+-----+------+----+--------+
推荐阅读
- php - 用户可以在我的网站上发布家长评论,但不能回复评论(即留下子评论)
- python - 按范围列出改组
- ios - SVGkit 不工作
- c++ - 重载 << 运算符作为“朋友”函数来打印 BST - C++
- javascript - 另一个页面上的AJAX调用方法
- go - 如何确定golang中连接的确切字节长度?
- php - 文件下载会破坏 txt 文件的格式
- mysql - 在Ubuntu16上使用nginx、phpmyadmin和mysql设置后Node应用无法连接数据库
- python-3.x - 使用 Python37 运行时使用 Cloud Functions 生成缩略图
- blender - .obj 文件的内部结构和与条件语句相关的顶点计算。