首页 > 解决方案 > 根据现有列与 pyspark 的交互,将新列添加到数据框

问题描述

我有一个由两列组成的数据框

+--------------+------------+
|             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]|
+--------------+------------+

架构:

 |-- A: string (nullable = true)
 |-- B: array (nullable = true)
 |    |-- element: string (containsNull = true)

我想添加一个新列,如果 A 和 B 的交集为空列表 ([]),则该列必须为 O,否则为 1。我尝试了下面的代码,但它似乎完全不正确

df.withColumn('Check', when (list((set(col('A'))&set(col('B')))) !=[] , 0).otherwise(1)).show()

感谢您的帮助

标签: pythondataframepyspark

解决方案


我想添加一个新列,如果 A 和 B 的交集为空列表 ([]),则该列必须为 O,否则为 1。

您可以直接使用 array_intersectsizewhen+otherwise

import pyspark.sql.functions as F
df.withColumn("Check",(F.size(F.array_intersect("A","B"))!=0).cast("Integer")).show()

或者:

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|
+------+---------+-----+

推荐阅读