有一个包含一列的DataFrame df_titles "title":
+--------------------+
| title|
+--------------------+
| harry_potter_1|
| harry_potter_2|
+--------------------+
我想知道在标题中出现的唯一术语的数量,这些术语用"_"分隔,并得到像这样的结果:
+--------------------+------+
| term| count|
+--------------------+------+
| harry| 2|
| potter| 2|
| 1| 1|
| 2| 1|
+--------------------+------+
我正在考虑创建一个new_df与列" ter"one_answers"count",对于df_titles中的每一行,拆分字符串并插入[string, 1]到new_df。然后可以通过" ter":
来减小新的dfval test = Seq.empty[Term].toDF()
df.foreach(spark.sql("INSERT INTO test VALUES (...)"))
...
但是我被代码困住了。我该怎么做?有更好的方法吗?
您可以使用spark内置函数,如split
和explode
来转换标题的数据框到术语的数据框,然后做一个简单的groupBy
。你的代码应该是:
import org.apache.spark.sql.functions.{col, desc, explode, split}
df_titles
.select(explode(split(col("title"), "_")).as("term"))
.groupBy("term")
.count()
.orderBy(desc("count")) // optional, to have count in descending order
通常,当您必须在数据框架上执行某些操作时,最好首先尝试使用spark内置函数的组合,这些函数可以在spark文档
中找到。详细信息从df_titles
开始:
+--------------+
|title |
+--------------+
|harry_potter_1|
|harry_potter_2|
+--------------+
split
创建一个由_
分隔的单词数组:
+-------------------+
|split(title, _, -1)|
+-------------------+
|[harry, potter, 1] |
|[harry, potter, 2] |
+-------------------+
然后,explode
在split
创建的数组中为每个项目创建一行:
+------+
|col |
+------+
|harry |
|potter|
|1 |
|harry |
|potter|
|2 |
+------+
.as("term")
将列col
重命名为term
:
+------+
|term |
+------+
|harry |
|potter|
|1 |
|harry |
|potter|
|2 |
+------+
则.groupBy("term")
与.count()
通过term
聚合计数,count()
是.agg(count("term").as("count"))
的快捷方式
+------+-----+
|term |count|
+------+-----+
|harry |2 |
|1 |1 |
|potter|2 |
|2 |1 |
+------+-----+
最后.orderBy(desc("count"))
的顺序是倒序的:
+------+-----+
|term |count|
+------+-----+
|harry |2 |
|potter|2 |
|1 |1 |
|2 |1 |
+------+-----+