python - 在不修改原始数据的情况下使用克隆数组数据的问题(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 = "•")
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()
解决方案
由于tdata
似乎是world
不存在复制属性的自定义类的实例,因此您可以使用复制模块中的方法对其进行复制:
import copy
graphdat = copy.deepcopy(tdata)
此后,graphdat
将tdata
是world
该类的不同实例。
推荐阅读
- ruby-on-rails - 使用 model.find 时,活动记录未返回特定列
- c++ - 为什么更改数组的第 0 个索引会比第 0 个索引更改更多?
- sql - 嵌套查询评估
- c# - 将 VBA 宏添加到 powerpoint
- c# - 编写自定义身份验证 + 我如何检查到哪个端点请求
- python - 将简单的 IDL 参数代码转换为 python 代码
- mysql - PhpMyAdmin 突然显示错误
- angular - 如何在源数组更改后从特定索引以角度启动引导轮播
- node.js - Webpack + Electron:如果应用程序没有它,为什么我需要“电子渲染器”脚本?
- ios - 我可以在没有 https 的情况下将我的应用程序发布到 App Store 吗?