[英]Python: Fastest Way to Traverse 2-D Array
我有一个2-D浮点数组,并且想要计算每列中大于阈值的字段数并将其存储在1-D数组中。 当前,我正在使用以下代码,但是要花很长时间(数组大小:27000 x 27000)。 谁能告诉我更快的方法。
以下是我的代码:
for Column in range(len(CorrelationData)):
BestMatchCount[0][Column] = sum(i >= Threshold for i in CorrelationData[:][Column])
您应该为此使用纯NumPy,Python的for循环会使其变慢:
>>> arr = np.random.rand(1000, 1000)
>>> %timeit [sum(i >= 0.5 for i in arr.T[c]) for c in xrange(len(arr))]
1 loops, best of 3: 1.58 s per loop
>>> %timeit np.sum(arr >= 0.5, axis=0)
1000 loops, best of 3: 1.53 ms per loop
最好的,但可能不是最简单的提高性能的方法是遵循分而治之的方法。 创建一个子胎面以遍历每列,并让线程进行所需的计算。 然后,所有线程完成并返回它们的值后,请编译这些值以找到您的结果。
编辑:添加了一些示例代码。 变量2DArray表示OP问题中的2d数组。
import threading
class Worker(threading.Thread):
def __init__(self, threadID, name, column):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.column = column
self.start()
def run(self):
# Do work here.
threadLock.acquire()
# Increment threshold counter here.
counter += self.doWork(self.column)
threadLock.release()
def doWork(self, colum):
count = 0
for row in column:
# Test if number is above threshold.
threadLock = threading.Lock()
threads = []
counter = 0
tid = 0
for column in 2DArray:
threads.append(Worker(tid, 'thread-{0}'.format(tid), column))
tid += 1
for thread in threads:
thread.join()
不幸的是,除非您使用向量化处理或其他并行方法作弊,否则列的总和非常严格地为O(n ^ 2)。 如果您的语言灵活,则R的隐式矢量化可能被证明是一个简单的解决方案。 如果不是这样的话,我认为与一些线程并行处理并使其连续完成可能是最快的方法(正如安德鲁在我之前所建议的那样)。
首先使用以下命令对数组进行排序
a = [5, 2, 3, 1, 4]
a.sort()
然后,您可以使用if命令。 一旦达到阈值,就可以停止搜索。
这可能会加快您的搜索速度。 在python中排序要快得多。
为了反转您的排序列表,您可以使用以下命令
def reverse_numeric(x, y):
return y - x
sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
[5, 4, 3, 2, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.