【问题标题】:reduce operation in spark returning dictionary instead dataframe减少火花返回字典而不是数据帧中的操作
【发布时间】:2018-04-29 17:25:18
【问题描述】:

我正在编写一个reduce 操作,我期待一个数据框而不是字典。根据下面的代码,它会给出字典

def funReduce(a, b):
    result = {}
    # first element
    if type(a) is tuple:
        result = a[1]
    else:
        result = a
    if b is not None:
        for key in list(b[1].keys()):
            if key not in result:
                result[key] = 1
            else:
                result[key] = result[key] + 1
    return result

d = sc.parallelize([(1305670057984, {(1000001256903, 1000001120912): 1, (1000001423245, 1000001120913): 1}), (1000001256903, {(1000001256903, 1000001120912): 1})])

s = d.reduce(funReduce)

我有一个类似于 d 的数据框,一个带有 Transaction id 的元组及其购买的产品(A->B 交易)和 count。所以我现在的目标是创建一个产品数量(A->B)的数据框,通过组合所有交易细节类似于以下内容:

{(1000001423245, 1000001120913): 1, (1000001256903, 1000001120912): 2}

使用上面的代码,我可以做到,但结果是字典。我需要一个数据框,以便进一步进行。因为如果它被转换为字典,那么在 Spark 中写这个没有意义。

【问题讨论】:

  • 如果您共享数据框的架构、输入数据框示例和预期数据框示例,将会很有帮助

标签: python-3.x apache-spark pyspark


【解决方案1】:

这只是一个字数,所以要么reduceByKey 得到RDD

d.values().flatMap(lambda d: ((x, 1) for x in d.keys())).reduceByKey(lambda x, y: x + y).collect()
# [((1000001423245, 1000001120913), 1), ((1000001256903, 1000001120912), 2)]

explodeagg

from pyspark.sql.functions import explode

spark.createDataFrame(d).select(explode("_2")).groupBy("key").count().show(truncate=False)
# +------------------------------+-----+
# |key                           |count|
# +------------------------------+-----+
# |[1000001423245, 1000001120913]|1    |
# |[1000001256903, 1000001120912]|2    |
# +------------------------------+-----+

获取DataFrame

【讨论】:

  • 而不是 count 你应该做 sum 聚合 ;)
猜你喜欢
  • 1970-01-01
  • 2017-05-13
  • 2020-01-21
  • 2017-05-24
  • 1970-01-01
  • 2019-03-24
  • 2016-04-29
相关资源
最近更新 更多