python - 根据现有列与 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()
感谢您的帮助
解决方案
我想添加一个新列,如果 A 和 B 的交集为空列表 ([]),则该列必须为 O,否则为 1。
您可以直接使用 array_intersectsize
和when+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|
+------+---------+-----+
推荐阅读
- c# - 如何从现有的 Windows 服务启动 AspNetCore 应用程序
- php - 用php调用sql函数
- intellij-idea - 是否可以在 Intellij IDEA 中将选择拆分为多个光标?
- python - 通过对象从 QuerySet 中获取下一个和上一个对象
- javascript - 动态翻译数据 react localize redux
- scala - 如何将 Scala 枚举用于 JOOQ 转换器
- sql - oracle sql 内联查询标识符无效
- django - 如何使用动态更新的 Choicefield 验证表单集?
- r - 在 hts 包中,为什么在创建组结构时 gts 功能硬编码 2-combinations?
- api - 在 Yammer 上哪里可以找到我的应用程序的 consumer_key?