要求:
- 我需要根据数据任意增加一个数组.
- 我可以猜测大小(大约100-200),但不能保证每次都适合该数组
- 一旦它增长到最终大小,我需要对其进行数值计算,因此我更希望最终使用二维numpy数组.
- 速度至关重要.例如,对于300个文件之一,update()方法被称为4500万次(大约需要150秒),而finalize()方法被称为500k次(总共需要106s)……总共需要250s大概.
这是我的代码:
def __init__(self): self.data = [] def update(self, row): self.data.append(row) def finalize(self): dx = np.array(self.data)我尝试过的其他事情包括以下代码...但这会比较慢.
Other things I tried include the following code ... but this is waaaaay slower.
def class A: def __init__(self): self.data = np.array([]) def update(self, row): np.append(self.data, row) def finalize(self): dx = np.reshape(self.data, size=(self.data.shape[0]/5, 5))以下是该调用方式的示意图:
Here is a schematic of how this is called:
for i in range(500000): ax = A() for j in range(200): ax.update([1,2,3,4,5]) ax.finalize() # some processing on ax推荐答案
我尝试了一些不同的操作,并设置了时间.
I tried a few different things, with timing.
import numpy as np
您提到的方法很慢:(32.094秒)
The method you mention as slow: (32.094 seconds) class A: def __init__(self): self.data = np.array([]) def update(self, row): self.data = np.append(self.data, row) def finalize(self): return np.reshape(self.data, newshape=(self.data.shape[0]/5, 5))
常规ol Python列表:(0.308秒)
Regular ol Python list: (0.308 seconds)
class B: def __init__(self): self.data = [] def update(self, row): for r in row: self.data.append(r) def finalize(self): return np.reshape(self.data, newshape=(len(self.data)/5, 5))
尝试以numpy实现数组列表:(0.362秒)
Trying to implement an arraylist in numpy: (0.362 seconds)
class C: def __init__(self): self.data = np.zeros((100,)) self.capacity = 100 self.size = 0 def update(self, row): for r in row: self.add(r) def add(self, x): if self.size == self.capacity: self.capacity *= 4 newdata = np.zeros((self.capacity,)) newdata[:self.size] = self.data self.data = newdata self.data[self.size] = x self.size += 1 def finalize(self): data = self.data[:self.size] return np.reshape(data, newshape=(len(data)/5, 5))
这是我的计时方式:
x = C() for i in xrange(100000): x.update([i])所以看起来常规的旧Python列表相当不错;)
So it looks like regular old Python lists are pretty good ;)
更多推荐
增长numpy数字数组的最快方法
发布评论