我是Spark编程的新手,当输入中出现一组值时,有一种方案来分配值。以下是我用来完成任务的传统SQL代码。需要在Spark中做同样的事情。
SQL代码:
SELECT CASE WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
ELSE 2 END AS Test
FROM Input c
我知道仅在一种情况下在火花中使用
when
。Input.select(when(Input.Number==1121231,1).otherwise(2).alias("Test")).show()
最佳答案
我假设您正在使用Spark DataFrames,而不是RDD。需要注意的一件事是,您可以直接在DataFrame上运行SQL查询:
# register the DataFrame so we can refer to it in queries
sqlContext.registerDataFrameAsTable(df, "df")
# put your SQL query in a string
query = """SELECT CASE WHEN
df.number IN ('1121231', '31242323') THEN 1 ELSE 2 END AS test
FROM df"""
result = sqlContext.sql(query)
result.show()
您还可以通过创建模仿查询的case语句的user-defined function来使用
select
:from pyspark.sql.types import *
from pyspark.sql.functions import udf
# need to pass inner function through udf() so it can operate on Columns
# also need to specify return type
column_in_list = udf(
lambda column: 1 if column in ['1121231', '31242323'] else 2,
IntegerType()
)
# call function on column, name resulting column "transformed"
result = df.select(column_in_list(df.number).alias("transformed"))
result.show()
关于apache-spark - Pyspark中带有IN子句的语句时的情况,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36874161/