增长 numpy 数值数组的最快方法 [英] Fastest way to grow a numpy numeric array

查看:52
本文介绍了增长 numpy 数值数组的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求:

  • 我需要根据数据增长一个任意大的数组.
  • 我可以猜测大小(大约 100-200),但不能保证每次都适合数组
  • 一旦它增长到最终大小,我需要对其进行数值计算,所以我更愿意最终得到一个二维 numpy 数组.
  • 速度至关重要.例如,对于 300 个文件中的一个,update() 方法被调用了 4500 万次(大约需要 150 秒),而 finalize() 方法被调用了 50 万次(总共需要 106 秒)……总共需要 250 秒

这是我的代码:

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

  1. 你提到的方法很慢:(32.094 秒)

  1. 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 数值数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆