【问题标题】:Counter function on a ArrayColumn Pyspark数组列 Pyspark 的计数器函数
【发布时间】:2018-01-24 16:10:21
【问题描述】:

来自这个数据框

+-----+-----------------+
|store|     values      |
+-----+-----------------+
|    1|[1, 2, 3,4, 5, 6]|
|    2|            [2,3]|
+-----+-----------------+

我想应用Counter 函数来得到这个:

+-----+------------------------------+
|store|     values                   |
+-----+------------------------------+
|    1|{1:1, 2:1, 3:1, 4:1, 5:1, 6:1}|
|    2|{2:1, 3:1}                    |
+-----+------------------------------+

我使用另一个问题的答案得到了这个数据框:

GroupBy and concat array columns pyspark

所以我尝试修改答案中的代码,如下所示:

选项 1:

def flatten_counter(val):
    return Counter(reduce (lambda x, y:x+y, val))

udf_flatten_counter = sf.udf(flatten_counter,     ty.ArrayType(ty.IntegerType()))
df3 = df2.select("store", flatten_counter("values2").alias("values3"))
df3.show(truncate=False)

选项 2:

df.rdd.map(lambda r: (r.store, r.values)).reduceByKey(lambda x, y: x + y).map(lambda row: Counter(row[1])).toDF(['store', 'values']).show()

但它不起作用。

有人知道我该怎么做吗?

谢谢

【问题讨论】:

    标签: apache-spark pyspark apache-spark-sql counter


    【解决方案1】:

    您只需提供正确的数据类型

    udf_flatten_counter = sf.udf(
        lambda x: dict(Counter(x)),
        ty.MapType(ty.IntegerType(), ty.IntegerType()))
    
    df = spark.createDataFrame(
       [(1, [1, 2, 3, 4, 5, 6]), (2, [2, 3])], ("store", "values"))
    
    
    df.withColumn("cnt", udf_flatten_counter("values")).show(2, False)
    # +-----+------------------+---------------------------------------------------+
    # |store|values            |cnt                                                |
    # +-----+------------------+---------------------------------------------------+
    # |1    |[1, 2, 3, 4, 5, 6]|Map(5 -> 1, 1 -> 1, 6 -> 1, 2 -> 1, 3 -> 1, 4 -> 1)|
    # |2    |[2, 3]            |Map(2 -> 1, 3 -> 1)                                |
    # +-----+------------------+---------------------------------------------------+
    

    与 RDD 类似

    df.rdd.mapValues(Counter).mapValues(dict).toDF(["store", "values"]).show(2, False)
    # +-----+---------------------------------------------------+
    # |store|values                                             |
    # +-----+---------------------------------------------------+
    # |1    |Map(5 -> 1, 1 -> 1, 6 -> 1, 2 -> 1, 3 -> 1, 4 -> 1)|
    # |2    |Map(2 -> 1, 3 -> 1)                                |
    # +-----+---------------------------------------------------+
    

    转换为dict 是必要的,因为显然Pyrolite 无法处理Counter 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2018-03-02
      • 2019-03-04
      • 1970-01-01
      • 2018-10-24
      • 2016-11-17
      相关资源
      最近更新 更多