使用pyspark从python运行自定义函数

问题描述 投票:0回答:2

我编写了一个自定义函数,该函数将从.txt文件中查找最多的单词。我需要通过PySpark作为RDD运行它

我编写了一个名为top_five的函数,唯一的参数是文件名

import collections

def top_five(file_name):    

    file = open(file_name, 'r', encoding = 'utf8')

    list1 = []
    for line in file:
        print(line)
        words = line.split()
        for i in words:
            j =''.join(filter(str.isalpha, i))
            j = j.lower()
            if len(j) > 5:
                list1.append(j)            

    count = collections.Counter(list1)

    most_occur = count.most_common(5)

    print("The most used words in the Applied Data Science Textbook is:")
    for item in most_occur:
        print("\t" + item[0] + " occured " + str(item[1]) + " times")

    return

实际结果必须是top_five函数的最后3行,其中它会打印每个单词和出现的次数

python apache-spark pyspark custom-function
2个回答
0
投票

尚不清楚上述对象中哪些与PySpark数据框相关,您最好在此处进行扩充。

将函数转换为PySpark UDF,这将使您可以将逻辑应用于PySpark数据框,而不必转换为Pandas并返回。

对于非常大的数据帧,众所周知,UDF的性能可能很差,运行时间很长。这也是我的个人经历。


0
投票

[如果可能,您应该完全使用Spark API,而不要尝试包装现有函数。

© www.soinside.com 2019 - 2024. All rights reserved.