2017-06-12 113 views
0

我試圖將列添加到數據幀指示,當兩個不同的值都在一個嵌套數組pyspark BITWISEAND VS符號操作

expr1 = array_contains(df.child_list, "value1") 
expr2 = array_contains(df.child_list, "value2") 

我得到了它與符號操作員工作中發現

df.select(...).withColumn("boolTest", expr1 & expr2) 

然後我嘗試用這種思想是與bitwiseAND替換此,我想有這些表情動態AND組合在一起的列表。

這因錯誤而失敗

df.select(...).withColumn("boolTest", expr1.bitwiseAND(expr2)) 

cannot resolve ..... due to data type mismatch: '(array_contains(c1.`child_list`, 'value1') & 
array_contains(c1.`child_list`, 'value2'))' requires integral type, 
not boolean;; 

有什麼區別和我究竟做錯了什麼?

回答

2

的&和|在pyspark BooleanType列運營商合作運營的邏輯AND和OR操作。換句話說,他們將True/False作爲輸入並輸出True/False。

的BITWISEAND功能由兩個數值的位AND'ing的確實位。所以他們可以取兩個整數並輸出它們的按位AND。

下面是每個的例子:

from pyspark.sql.types import * 
from pyspark.sql.functions import * 

schema = StructType([ 
    StructField("b1", BooleanType()), 
    StructField("b2", BooleanType()), 
    StructField("int1", IntegerType()), 
    StructField("int2", IntegerType()) 
]) 
data = [ 
    (True, True, 0x01, 0x01), 
    (True, False, 0xFF, 0xA), 
    (False, False, 0x01, 0x00) 
] 

df = sqlContext.createDataFrame(sc.parallelize(data), schema) 


df2 = df.withColumn("logical", df.b1 & df.b2) \ 
     .withColumn("bitwise", df.int1.bitwiseAND(df.int2)) 

df2.printSchema() 
df2.show() 

+-----+-----+----+----+-------+-------+ 
| b1| b2|int1|int2|logical|bitwise| 
+-----+-----+----+----+-------+-------+ 
| true| true| 1| 1| true|  1| 
| true|false| 255| 10| false|  10| 
|false|false| 1| 0| false|  0| 
+-----+-----+----+----+-------+-------+ 


>>> df2.printSchema() 
root 
|-- b1: boolean (nullable = true) 
|-- b2: boolean (nullable = true) 
|-- int1: integer (nullable = true) 
|-- int2: integer (nullable = true) 
|-- logical: boolean (nullable = true) 
|-- bitwise: integer (nullable = true) 

如果要動態,共同列的列表,你可以做這樣的:

columns = [col("b1"), col("b2")] 
df.withColumn("result", reduce(lambda a, b: a & b, columns)) 
+0

拉姆達解決方案肯定會工作。我誤會我以爲不知何故'bitwiseAND'功能被連接到'&'操作符的重載,但是我錯了 - 'bitwiseAND'的確是位與,即使操作者通常在與位與行爲之間的關係邏輯容量。 – wrschneider