pyspark中的计数器以检查重复数组中的数组

时间:2019-03-28 09:23:02

标签: python sql collections pyspark counter

我有一个数据帧df1

id     transactions
1      [1, 3,3,3,2,5]
2      [1,2]
root
 |-- id: int (nullable = true)
 |-- transactions: array (nullable = false)
      |-- element: string(containsNull = true)
None

我有一个数据框df2

items         cost
[1, 3,3, 5]    2
[1, 5]      1

root
|-- items: array (nullable = false)
  |-- element: string (containsNull = true)
 |-- cost: int (nullable = true)
None

我必须检查物品是否在交易中,如果是这样,则要合计费用。 [1,3,3,3,5]中的[1,3,3,5]为True,[1,2]中的[1,3,3,5]为False,依此类推。

结果应为

id     transactions   score
1      [1,3,3,3,5]    3
2      [1,2]          null

我尝试爆炸并加入(内部,left_semi)方法,但由于重复而全部失败。 Check all the elements of an array present in another array pyspark issubset(),array_intersect()也不起作用。

我遇到了Python - verifying if one list is a subset of the other。我发现以下解决了这个问题并且效率很高。

from collections import Counter
not Counter([1,3,3,3,5])-Counter([1,3,3,4,5])
False
>>> not Counter([1,3,3,3,5])-Counter([1,3,3,5])
False
>>> not Counter([1,3,3,5])-Counter([1,3,3,3,5])
True

我尝试了以下

@udf("boolean")
def contains_all(x, y):
if x is not None and y is not None:
    return not (lambda y: dict(Counter(y)))-(lambda x: dict(Counter(x)))


(df1
.crossJoin(df2).groupBy("id", "transactions")
.agg(sum_(when(
    contains_all("transactions", "items"), col("cost")
)).alias("score"))
.show())

但是会引发错误。  文件“”,第39行,在contains_all中 TypeError:-:“功能”和“功能”的不受支持的操作数类型

还有其他方法可以实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

只是更新了udf以保留重复项,并且不确定性能,

from pyspark.sql.functions import udf,array_sort,sum as sum_,when,col

dff = df1.crossjoin(df2)

dff = dff.withColumn('transaction',array_sort('transaction')).\
      withColumn('items',array_sort('items')) ## sorting here,it's needed in UDF

+---+---------------+------------+----+
| id|    transaction|       items|cost|
+---+---------------+------------+----+
|  1|[1, 2, 3, 3, 5]|[1, 3, 3, 5]|   2|
|  1|[1, 2, 3, 3, 5]|      [1, 5]|   1|
|  2|         [1, 2]|[1, 3, 3, 5]|   2|
|  2|         [1, 2]|      [1, 5]|   1|
+---+---------------+------------+----+

@udf('boolean')
def is_subset_w_dup(trans,itm):
    itertrans = iter(trans)
    return all(i in itertrans for i in itm)


dff.groupby('id','transaction').agg(sum_(when(is_subset_w_dup('transaction','items'),col('cost'))).alias('score')).show()

+---+---------------+-----+
| id|    transaction|score|
+---+---------------+-----+
|  2|         [1, 2]| null|
|  1|[1, 2, 3, 3, 5]|    3|
+---+---------------+-----+