增长numpy数字数组的最快方法

编程入门 行业动态 更新时间:2024-10-08 22:13:55
本文介绍了增长numpy数字数组的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

要求:

  • 我需要根据数据任意增加一个数组.
  • 我可以猜测大小(大约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数字数组的最快方法

    本文发布于:2023-11-30 18:24:53,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1651058.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数组   最快   数字   方法   numpy

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!