首页 > 解决方案 > 在不修改原始数据的情况下使用克隆数组数据的问题(Python)

问题描述

我有一个 Python 入门课程的项目要做,但由于一个问题,我被困在接近尾声的地方。

我的问题是以下一个:我想使用由名为“world”的类的不同属性的值组成的双重“tdata”数据框对其进行更改。(试图用指标的当前水平做一些预测)我试图通过生成一个新的数据框“graphdat”来做到这一点,我在函数中使用它来生成图表。

我的问题是,最后,我的“tdata”数组也被修改了。

我尝试使用 graphdat = tdata.copy() ,但它返回一个 AttributeError :“world”对象没有属性“copy”。

任何人都会知道我怎么能以另一种方式做到这一点?

谢谢!

def graph_ppm(self):
        self.price_ppm = 10
        self.budget -= self.price_ppm
        period = tdata.period
        
        graphdat = tdata

        while period < 30:
            period +=1
            graphdat.sup = (graphdat.emit - graphdat.absorb)
            graphdat.ppm += graphdat.sup


            yppm.append(round(graphdat.ppm,2)) 

编辑:

我想我误解了整个问题。正如Md Imbesat Hassan Rizvi所建议的那样,我决定使用 graphdat = copy.deepcopy(tdata) 但我想多次使用此函数,我确实想将 graphdat 重新初始化为参数的当前级别和当前周期。问题是,如果多次运行此函数,我会获得这种图表:

图形

我的最大周期是 30,我想摆脱过去的值来创建一个非常新的图表。

def graph_temp(self):

    self.price_temp = 10
    self.budget -= self.price_temp
    
    graphdat = copy.deepcopy(tdata)
    period = graphdat.period
    plx.clear_plot()

    while period < 30:
        period +=1
        graphdat.sup = (graphdat.emit - graphdat.absorb)
        graphdat.ppm += graphdat.sup

        if graphdat.ppm <380: 
            graphdat.temperature += graphdat.sup * 0.001
        if graphdat.ppm <400: 
            graphdat.temperature += (graphdat.sup) * 0.001
        if graphdat.ppm <450:
            graphdat.temperature += (graphdat.sup) * 0.005
            graphdat.pop_satisfaction -=1
        else:
            graphdat.temperature += (graphdat.sup) * 0.01


        ytemp.append(round(graphdat.temperature,2)) 

    limittemp = [2]*31
    recomtemp = [1.5]*31

    plx.plot(ytemp, label="Temperatures forecast",line_marker = "•&quot;)
    plx.plot(limittemp, label="Catastrophe level",line_marker = "-")
    plx.plot(recomtemp, label="Limit level after period 30",line_marker = "=")
    plx.xlabel('Temperatures')
    plx.ylabel('Period')
    plx.title('Title')
    plx.figsize(50, 25)
    plx.ticks(31, 11)

    return plx.show()

标签: pythonpandasloopsincrement

解决方案


由于tdata似乎是world不存在复制属性的自定义类的实例,因此您可以使用复制模块中的方法对其进行复制:

import copy
graphdat = copy.deepcopy(tdata)

此后,graphdattdataworld该类的不同实例。


推荐阅读