[英]How to better count occurrences of a list in another list and then list the results for each element using count
我想要一种faster
的方法让 Pandas python 计算listA
中每个元素的出现次数listB
并将计数次数计入listC
。 例如
listA = [1,2,3,4,5,6,7] listB = [1,1,5,4,8,3,4,7,9,2,1,4,7,6,2,4,5,6,3] output: listC = [3,2,2,4,2,2,2]
listA
有800 000
元素,而listB
有2million
个元素。
我正在使用以下代码,但使用 Pandas 处理需要很长时间。
listC =[listB.count(x) for x in listA]
您可以使用collections.Counter
来加速任务:
from collections import Counter
listA = [1, 2, 3, 4, 5, 6, 7]
listB = [1, 1, 5, 4, 8, 3, 4, 7, 9, 2, 1, 4, 7, 6, 2, 4, 5, 6, 3]
c = Counter(listB)
listC = [c.get(v) for v in listA]
print(listC)
印刷:
[3, 2, 2, 4, 2, 2, 2]
或者:使用np.bincount
:
count_arr = np.bincount(listB)
print([count_arr[x] for x in listA])
印刷:
[3, 2, 2, 4, 2, 2, 2]
我想对大量数据进行排序的想法是不可能的?
只是我认为如果对数据进行排序,count()可能会工作得更快,因为相似的值放在相邻的 position 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.