【问题标题】:combining lists inside values in pyspark在pyspark中组合值内的列表
【发布时间】:2016-04-10 01:14:35
【问题描述】:

在 RDD 上执行收集给了我一个列表。我使用代码对其进行了迭代以打印结构,

for entry in ratings_and_users.collect():
        print(entry)

输出是,

(b'"20599"', ([7.0, b'"349802972X"'], ['bamberg, franken, germany', 'NULL']))
(b'"120675"', ([0.0, b'"0972189408"'], ['crescent city, california, usa', 45]))
(b'"166487"', ([6.0, b'"8422626993"'], ['santander, n/a, spain', 103]))
(b'"166487"', ([7.0, b'"8440639228"'], ['santander, n/a, spain', 103]))

在 pyspark 中,我需要编写一个 lambda,将值中的所有列表连接到一个列表中。例如,在上面的输出中,每一行都是一个键值对,键b'"166487"' 有一个列表作为它的值([7.0, b'"8440639228"'], ['santander, n/a, spain', 103])。该值包含多个列表,如何在 RDD 上执行 collect 之前将它们加入单个列表

所需的输出结构:

(b'"166487"', ([7.0, b'"8440639228"', 'santander, n/a, spain', 103]))

【问题讨论】:

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


    【解决方案1】:

    问题是我将收集操作结果中的每个项目都视为键值对,但它是Tuple,其中键作为第一个条目和值,第二个。所以我反复使用下面的lambda,我得到了结果。

    def append_values_inside(key, value):
        temp = []
        for v in value:
            for entry in v:
                temp.append(entry)
        return (key, temp)
    for entry in ratings_and_users.map(lambda a: append_values_inside(a[0], a[1])).collect() :
            print(entry)
    

    最终结果:

    (b'"20599"', [7.0, b'"349802972X"', 'bamberg, franken, germany', 'NULL'])
    (b'"120675"', [0.0, b'"0972189408"', 'crescent city, california, usa', 45])
    (b'"166487"', [6.0, b'"8422626993"', 'santander, n/a, spain', 103])
    (b'"166487"', [7.0, b'"8440639228"', 'santander, n/a, spain', 103])
    

    【讨论】:

    • 嗯,你可以先做那张地图collect
    • @AlbertoBonsanto Nice catch 我纠正了代码中的错误,但忘记在 SO 中更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多