【问题标题】:IndexError: list index out of range while using reduceByKey operation on pyspark shellIndexError:在pyspark shell上使用reduceByKey操作时列出索引超出范围
【发布时间】:2019-04-15 03:36:18
【问题描述】:

目标:从 youtube 数据集中找到最高的视频类别

使用:Pyspark 外壳

预期:类别及其出现次数

实际:使用 reduceBykey 作为 IndexError 时出错:列表索引超出范围

我试过下面的代码:

data="/Users/sk/Documents/GitRepository/Udemy_BigData_spark/1.txt"
input = sc.textFile(data)
results = input.map(lambda x: (x.split(‘\t')[3].encode("utf-8").replace('"', '').replace("'", '')))results.take(20)

这给出了以下结果:

['Comedy', 'Comedy', 'Entertainment', 'People & Blogs', 'People &
Blogs', 'Music', 'Comedy', 'People & Blogs', 'Entertainment',
'Entertainment', 'Entertainment', 'Entertainment', 'Entertainment',
'Entertainment', 'Entertainment', 'Entertainment', 'Entertainment',
'Entertainment', 'Entertainment', 'Entertainment']


results=results.map(lambda x: (x,1))

这给出了以下结果:

[('Comedy', 1), ('Comedy', 1), ('Entertainment', 1), ('People & Blogs', 1), ('People & Blogs', 1), ('Music', 1), ('Comedy', 1), ('People & Blogs', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1), ('Entertainment', 1)]


results=results.reduceByKey(lambda x, y: x + y)    
results.take(20)

这给出了一个巨大的错误:(

我希望它显示如下结果:

(179049,Music), (127674,Entertainment), (87818,Comedy), (73293,Film &
Animation), (67329,Sports)

【问题讨论】:

    标签: apache-spark pyspark


    【解决方案1】:

    我写的代码是在scala中的;

    val ds = Seq("A", "B", "C", "A", "B", "C", "D", 
                 "E", "F", "G", "A")
      .toDF.as[String].map(x => (x, 1))
    ds.groupByKey(x => x._1)
      .reduceGroups((l, r) => (l._1, l._2+r._2))
      .show
    

    输出:

    +-----+------------------------------+
    |value|ReduceAggregator(scala.Tuple2)|
    +-----+------------------------------+
    |    F|                        [F, 1]|
    |    E|                        [E, 1]|
    |    B|                        [B, 2]|
    |    D|                        [D, 1]|
    |    C|                        [C, 2]|
    |    A|                        [A, 3]|
    |    G|                        [G, 1]|
    +-----+------------------------------+
    

    【讨论】:

    • 嘿 Elior,我正在寻找 python 代码。使用 scala 我可以得到这个工作。但是作业是与 pyspark 一起工作的 :(
    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2019-09-08
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多