Reputation: 303
I have a dataframe which consists of two columns
+--------------+------------+
| A| B|
+--------------+------------+
| [b, c]| [a, b, c]|
| [a]| [c, d]|
| [a, c]| [b, c, e]|
| [b, c]| [a, b]|
| [a]| [a, d, e]|
| [a, c]| [b]|
+--------------+------------+
Schema:
|-- A: string (nullable = true)
|-- B: array (nullable = true)
| |-- element: string (containsNull = true)
I want to add a new column which must be O if the intersection of A and B is empty list ([]) and 1 otherwise. I tried the code below but it seem incorrect at all
df.withColumn('Check', when (list((set(col('A'))&set(col('B')))) !=[] , 0).otherwise(1)).show()
Thank you for your help
Upvotes: 1
Views: 59
Reputation: 75140
I want to add a new column which must be O if the intersection of A and B is empty list ([]) and 1 otherwise.
You can directly use array_intersect with size
and when+otherwise
import pyspark.sql.functions as F
df.withColumn("Check",(F.size(F.array_intersect("A","B"))!=0).cast("Integer")).show()
or:
df.withColumn("Check",F.when(F.size(F.array_intersect("A","B"))==0,0).otherwise(1)).show()
+------+---------+-----+
| A| B|Check|
+------+---------+-----+
|[b, c]|[a, b, c]| 1|
| [a]| [c, d]| 0|
|[a, c]|[b, c, e]| 1|
|[b, c]| [a, b]| 1|
| [a]|[a, d, e]| 1|
|[a, c]| [b]| 0|
+------+---------+-----+
Upvotes: 3