首页 > 解决方案 > 如何使用 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 中实现这一点?我是新手,非常感谢您的帮助!

标签: pythonapache-sparkpyspark

解决方案


首先,从数据创建 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,分解textand 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|
+----+-----+

推荐阅读