我有一個包含字串的串列串列,我想計算每個元素出現的串列數量:
list_of_lists = [["dog", "cow"], ["dragon", "ox", "cow"], ["fox", "cow", "dog"]]
因此,cow出現在 3 個串列中,dog出現在 2 個等中。
對于這么小的資料集,我通常會這樣做:
from collections import Counter
from itertools import chain
count = Counter(chain.from_iterable(set(x) for x in list_of_lists))
因此:
print(count["dog"])
2
但是,我想使用 PySpark 和 MapReduce 對大型資料集執行此操作,以便對于串列串列中的每個元素,我將具有上述計數器值:
[("dog", 2),
("cow", 3),
("dragon", 1),
("ox", 1),
("fox", 1)]
等等。
我正在嘗試這樣的事情:
list_of_lists = sc.parallelize(list_of_lists)
list_occurencies = list_of_lists.map(lambda x: x, count[x])
沒有效果
uj5u.com熱心網友回復:
使用flatMap扁平化嵌套的陣列,然后reduceByKey獲得串列中的每個單詞的計數:
list_of_lists = sc.parallelize(list_of_lists)
list_of_lists = list_of_lists.flatMap(lambda x: set(x))\
.map(lambda x: (x, 1))\
.reduceByKey(lambda a, b: a b)
print(list_of_lists.collect())
# [('fox', 1), ('dragon', 1), ('ox', 1), ('dog', 2), ('cow', 3)]
uj5u.com熱心網友回復:
子串列似乎不包含重復條目,因為您在set那里使用。在這種情況下,我建議將您的串列展平并計算每個專案的頻率。
我將以下串列展平函式應用于串列串列并使用collections.Counter.
def flatten_list(lsts):
out = []
for l in lsts:
out = l
return out
我使用以下內容生成串列串列:
import random
random.seed(420)
lsts = []
for i in range(10000):
n = random.randint(10,100)
lsts.append(random.sample(range(n),int(n/2)))
并對計數器計時:
%timeit y = Counter(chain.from_iterable(set(x) for x in lsts))
8.37 ms ± 408 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit x = Counter(flatten_list(lsts))
5.37 ms ± 278 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
它可能不是您正在尋找的那種解決方案,但它是一個想法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383920.html
