python numpy向量化对象实例数组

时间:2018-11-13 13:41:42

标签: pandas class numpy object vectorization

我想将我的calc函数及其所有参数封装在一个对象中,但是将数百万个对象的执行向量化,就像numpy会做的那样。有什么建议吗?

计算仍然是numpy应该能够向量化的基本算法。

示例代码:

import numpy as np
myarray = np.random.rand(3, 10000000)

############################# This works fine: FAST ###################################

def calc(a,b,c):
    return (a+b/c)**b/a


res1 = calc(*myarray)  #0.7 seconds

############################# What I'd like to do (unsuccessfully): SLOW ###################################

class MyClass():
    __slots__ = ['a','b','c']

    def __init__(self, a,b,c):
        self.a, self.b, self.c = a,b,c

    def calc(self):
        return (self.a + self.b / self.c) ** self.b / self.a 

def classCalc(myClass:MyClass):
    return myClass.calc()

vectorizedClassCalc = np.vectorize(classCalc)
myobjects = np.array([MyClass(*args) for args in myarray.transpose()])


res2 = vectorizedClassCalc(myobjects) #8 seconds no different from a list comprehension
res3 = [obj.calc() for obj in myobjects] #7.5 seconds 

也许熊猫还有其他功能?

0 个答案:

没有答案