这几种写法If-Else
/ When-Then-Else
/ When-Otherwise
表达于pyspark
.
示例数据框
df = spark.createDataFrame([(1,1),(2,2),(3,3)],['id','value'])
df.show()
#+---+-----+
#| id|value|
#+---+-----+
#| 1| 1|
#| 2| 2|
#| 3| 3|
#+---+-----+
#Desired Output:
#+---+-----+----------+
#| id|value|value_desc|
#+---+-----+----------+
#| 1| 1| one|
#| 2| 2| two|
#| 3| 3| other|
#+---+-----+----------+
Option#1: withColumn()
使用“当-否则”
from pyspark.sql.functions import when
df.withColumn("value_desc",when(df.value == 1, 'one').when(df.value == 2, 'two').otherwise('other')).show()
Option#2: select()
使用“当-否则”
from pyspark.sql.functions import when
df.select("*",when(df.value == 1, 'one').when(df.value == 2, 'two').otherwise('other').alias('value_desc')).show()
Option3: selectExpr()
使用 SQL 等效 CASE 表达式
df.selectExpr("*","CASE WHEN value == 1 THEN 'one' WHEN value == 2 THEN 'two' ELSE 'other' END AS value_desc").show()
类似SQL的表达式也可以写成withColumn()
and select()
using pyspark.sql.functions.expr功能。以下是示例。
Option4: select()
使用 expr 函数
from pyspark.sql.functions import expr
df.select("*",expr("CASE WHEN value == 1 THEN 'one' WHEN value == 2 THEN 'two' ELSE 'other' END AS value_desc")).show()
Option5: withColumn()
使用 expr 函数
from pyspark.sql.functions import expr
df.withColumn("value_desc",expr("CASE WHEN value == 1 THEN 'one' WHEN value == 2 THEN 'two' ELSE 'other' END AS value_desc")).show()
Output:
#+---+-----+----------+
#| id|value|value_desc|
#+---+-----+----------+
#| 1| 1| one|
#| 2| 2| two|
#| 3| 3| other|
#+---+-----+----------+