python - 如何使用 Python 计算 Spark 中带有键的记录数?
问题描述
我的数据显示了一些单词对以及这对单词出现的次数。例如:
[("('best', 'it')", 3), ("('best', 'of')", 4), ("('best', 'the')", 3), ("('best', 'was')", 3), ("('it', 'of')", 11), ("('it', 'the')", 11)]
我的目标是计算一个单词,它存在多少对。例如,我想得到:
best 4
it 3
一件棘手的事情是,“它”不仅出现在
("('it', 'of')", 11), ("('it', 'the')", 11)
但也发生在
('best', 'it')", 3)
因此程序需要以某种方式识别它。
我应该如何使用 Python 在 Spark 中实现这一点?我是新手,非常感谢您的帮助!
解决方案
首先,从数据创建 pyspark 数据框。
df = sql.createDataFrame(
[("('best', 'it')", 3),\
("('best', 'of')", 4),\
("('best', 'the')", 3),\
("('best', 'was')", 3),\
("('it', 'of')", 11),\
("('it', 'the')", 11)],
['text', 'count'])
df.show()
+---------------+-----+
| text|count|
+---------------+-----+
| ('best', 'it')| 3|
| ('best', 'of')| 4|
|('best', 'the')| 3|
|('best', 'was')| 3|
| ('it', 'of')| 11|
| ('it', 'the')| 11|
+---------------+-----+
text
然后,转换in的字符串Array
,分解text
and groupby
。
import pyspark.sql.functions as F
import ast
convert_udf = F.udf(lambda x: ast.literal_eval(x), ArrayType(StringType()) )
df = df.withColumn('text', convert_udf('text'))\
.withColumn('text', F.explode('text'))\
.groupby('text').count()
df.show()
+----+-----+
|text|count|
+----+-----+
| was| 1|
| it| 3|
| the| 2|
| of| 2|
|best| 4|
+----+-----+
推荐阅读
- c++ - 类专业化中的clang / gcc不一致
- unity3d - 为什么即使一切都很好,我的玩家移动也不起作用?
- node.js - 如何为节点 repl 创建别名?
- python - 在python中基于文件名中的字符串移动文件
- java - 在基于 Java 的应用程序中启用 LdapEnforceChannelBinding
- python - 如何替换文件的内容?
- c# - 来自 cshtml 文件的 KeyNotFoundException
- marklogic - MarkLogic - 管理员级别限制集合
- powershell - Powershell - 在 Powershell ISE 中在 Powershell 中运行多行脚本
- reactjs - React TypeScript Jest 酶测试