簡體   English   中英

根據現有列與 pyspark 的交互,將新列添加到 dataframe

[英]Add new column to dataframe depending on interqection of existing columns with pyspark

我有一個 dataframe 由兩列組成

+--------------+------------+
|             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_intersect 與sizewhen+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|
+------+---------+-----+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM