如何在 OO 中轻松高效地存储 numpy ufuncs 的模拟数据

在 jupyter notebook 中,我对资源进行 OO 建模,但在控制循环中需要聚合多个对象的数据,与 ufunc 和类似操作相比效率低下。

为了打包功能,我选择了面向对象,但为了高效简洁的代码,我可能必须将数据提取到存储类中(可能)并将所有 ri[0] 行推送到二维数组中,在本例中为 (2,K)。该类不需要日志,只需要最后一个条目。


K = 100

class Resource:


    def __init__(self):

        self.log = np.random( (5,K) )

        # log gets filled during simulation


r0 = Resource()

r1 = Resource()


# while control loop:

    #aggregate control data

    for k in K:

        total_row_0 = r0.log[0][k] + r1.log[0][k]

    #do sth with the totals and loop again

这将大大提高性能,但如果单独存储,我很难将数据链接到类。你会如何处理这个问题?pandas DataFrames、np View 还是浅拷贝?


[[...] #r0

 [...] ]#r1 same data into one array, efficient but map back to class difficult 


qq_遁去的一_1
浏览 128回答 1
1回答

海绵宝宝撒

这是我的看法:import numpy as npK = 3class Res:    logs = 2    def __init__(self):        self.log = None    def set_log(self, view):        self.log = viewbatteries = [Res(),  Res()]d = {'Res': np.random.random( (Res.logs * len(batteries), K) )}        for i in range(len(batteries)):    view = d['Res'].view()[i::len(batteries)][:]    batteries[i].set_log(view)print(d)batteries[1].log[1][2] = 1#test modifies view of last entry of second Res of second logprint(d)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python