PySpark DataFrame使用多个when条件的withColumn函数

3

我如何使用多个条件实现以下目标。

from pyspark.sql import functions as F
df = spark.createDataFrame([(5000, 'US'),(2500, 'IN'),(4500, 'AU'),(4500, 'NZ')],["Sales", "Region"])
df.withColumn('Commision', 
              F.when(F.col('Region')=='US',F.col('Sales')*0.05).\
              F.when(F.col('Region')=='IN',F.col('Sales')*0.04).\
              F.when(F.col('Region')in ('AU','NZ'),F.col('Sales')*0.04).\
              otherwise(F.col('Sales'))).show()

2
只需将第二个和第三个F.when更改为when - jxc
1
in 转换为 .isin('AU', 'NZ') - murtihash
2个回答

4
在使用 when 后使用 otherwise:
df.withColumn('Commision',
              F.when(F.col('Region') == 'US', F.col('Sales') * 0.05).otherwise(
                F.when(F.col('Region') == 'IN', F.col('Sales') * 0.04).otherwise(
                    F.when(F.col('Region').isin('AU', 'NZ'), F.col('Sales') * 0.04).otherwise(
                        F.col('Sales'))))).show()

+-----+------+---------+
|Sales|Region|Commision|
+-----+------+---------+
| 5000|    US|    250.0|
| 2500|    IN|    100.0|
| 4500|    AU|    180.0|
| 4500|    NZ|    180.0|
+-----+------+---------+

2

我认为你在条件语句中缺少了.isin,并且只需在第一个when条件中使用F.when(或)使用.when

from pyspark.sql import functions as F
df = spark.createDataFrame([(5000, 'US'),(2500, 'IN'),(4500, 'AU'),(4500, 'NZ')],["Sales", "Region"])
df.withColumn('Commision', 
              F.when(F.col('Region')=='US',F.col('Sales')*0.05).\
              when(F.col('Region')=='IN',F.col('Sales')*0.04).\
              when(F.col('Region').isin ('AU','NZ'),F.col('Sales')*0.04).\
              otherwise(F.col('Sales'))).show()

#+-----+------+---------+
#|Sales|Region|Commision|
#+-----+------+---------+
#| 5000|    US|    250.0|
#| 2500|    IN|    100.0|
#| 4500|    AU|    180.0|
#| 4500|    NZ|    180.0|
#+-----+------+---------+

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接