2016-05-16 55 views
0

我有一個pyspark DataFrame,比如說df1,有多列。基於Pyspark中的列表和列創建列

我也有一個列表,比如l = ['a','b','c','d'],這些值是DataFrame中某列中存在的值的子集。現在

,我願做這樣的事情:

df2 = df1.withColumn('new_column', expr("case when col_1 in l then 'yes' else 'no' end")) 

但這是拋出以下錯誤:

failure: "(" expected but identifier l found.

任何想法如何解決此錯誤或做什麼更好的辦法它?

回答

3

你可以做到這一點與Column對象的isin功能:

df1 = sqlContext.createDataFrame([('a', 1), ('b', 2), ('c', 3)], ('col1', 'col2')) 
l = ['a', 'b'] 

from pyspark.sql.functions import * 
df2 = df1.withColumn('new_column', when(col('col1').isin(l), 'yes').otherwise('no')) 

df2.show() 

+----+----+----------+ 
|col1|col2|new_column| 
+----+----+----------+ 
| a| 1|  yes| 
| b| 2|  yes| 
| c| 3|  no| 
+----+----+----------+ 

注:星火< 1.5,使用inSet代替isin

參考:pyspark.sql.Columndocumentation

+0

它的工作。非常感謝! :) – Hemant