【问题标题】:reduce by matching lower case keys in spark rdd通过匹配 spark rdd 中的小写键来减少
【发布时间】:2021-08-16 12:07:42
【问题描述】:

我有一个 (key, value) 对的 rdd,键是字符串,值是字符串的出现次数。

words.take(10)

Out[98]: [('The', 2767),
 ('Project', 83),
 ('the', 3),
 ('of', 14941),
 ('Leo', 4),
 ('is', 3245),
 ('use', 80),
 ('anyone', 191),
 ('Of', 25),
 ('at', 4235)]

我想通过 key.lower() 匹配键,对它们的值求和,并为每个大写/小写键保留原始值。

另外,我想过滤掉不重复的键。

所以我上面的 words.take(10) 示例的输出将是:

 [(('The', 2767),('the', 3),2770),(('Of', 25),('of', 14941),14966)]

【问题讨论】:

    标签: python apache-spark rdd


    【解决方案1】:

    您可以将groupbycollect_listfilter 一起使用,数据如下

    from pyspark.sql import functions as f
    
    data = [
        ('The', 2767),
        ('Project', 83),
        ('the', 3),
        ('of', 14941),
        ('Leo', 4),
        ('is', 3245),
        ('use', 80),
        ('anyone', 191),
        ('Of', 25),
        ('at', 4235)
    ]
    
    df = spark.createDataFrame(data).toDF(*["word", "count"])
    
    df.groupby(f.lower("word").alias("word")) \
      .agg(f.collect_list(f.struct("word", "count")).alias("list"), f.sum("count").alias("sum")) \
      .filter(f.size("list") > 1) \
      .select("list", "sum") \
      .show(truncate=False)
    

    输出:

    +-----------------------+-----+
    |list                   |sum  |
    +-----------------------+-----+
    |[{The, 2767}, {the, 3}]|2770 |
    |[{of, 14941}, {Of, 25}]|14966|
    +-----------------------+-----+
    

    【讨论】:

    • 请导入函数为from pyspark.sql import functions as f
    猜你喜欢
    • 2016-12-05
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2019-10-02
    • 2021-05-24
    • 2016-03-06
    • 2016-11-27
    • 2018-11-19
    相关资源
    最近更新 更多