【问题标题】:Using rlike with list to create new df scala使用 rlike 和 list 创建新的 df scala
【发布时间】:2021-03-25 23:20:13
【问题描述】:

2 天前刚开始使用 scala。

事情是这样的,我有一个 df 和一个列表。 df 包含两列:段落和作者,列表包含单词(字符串)。我需要计算列表中每个单词都由作者出现的所有段落的计数。

到目前为止,我的想法是在列表上创建一个 for 循环以使用 rlike 查询 df 并创建一个新的 df,但即使这确实有效,我也不知道该怎么做。任何帮助表示赞赏!

编辑:添加示例数据和预期输出

// Example df and list
val df = Seq(("auth1", "some text word1"), ("auth2","some text word2"),("auth3", "more text word1").toDF("a","t")

df.show

+-------+---------------+
|      a|              t|
+-------+---------------+
|auth1  |some text word1|
|auth2  |some text word2|
|auth1  |more text word1|
+-------+---------------+
    
val list = List("word1", "word2")
    
// Expected output

 newDF.show

+-------+-----+----------+
|   word|    a|text count|
+-------+-----+----------+
|word1  |auth1|         2|
|word2  |auth2|         1|
+-------+-----+----------+

【问题讨论】:

    标签: scala dataframe apache-spark apache-spark-sql


    【解决方案1】:

    您可以对列表中的每个单词进行过滤和聚合,并使用unionAll 组合所有生成的数据帧:

    val result = list.map(word => 
        df.filter(df("t").rlike(s"\\b${word}\\b"))
          .groupBy("a")
          .agg(lit(word).as("word"), count(lit(1)).as("text count"))
    ).reduce(_ unionAll _)
    
    result.show
    +-----+-----+----------+
    |    a| word|text count|
    +-----+-----+----------+
    |auth3|word1|         1|
    |auth1|word1|         1|
    |auth2|word2|         1|
    +-----+-----+----------+
    

    【讨论】:

      猜你喜欢
      • 2019-03-18
      • 2019-04-26
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2020-10-20
      相关资源
      最近更新 更多