Python脚本不断向fi输出2个元素

2024-04-26 15:06:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试集成scipy书中的僵尸启示录代码,我做了一个特别的调整,其中没有在特定的时间内与numpy.linspace,我想循环一个不断增加的时间和不断变化的时间。你知道吗

但我遇到了一个障碍,每当我输出到一个数据帧文件时,总是有2个元素对被输出,所以循环输出到2行,而实际上我只需要将最终状态记录到一个文件中。这很难解释,但一旦运行就更容易看到:

import matplotlib.pyplot as plt
from scipy.integrate import odeint
import pandas as pd

plt.ion()
plt.rcParams['figure.figsize'] = 10, 8

P = 0      # birth rate
d = 0.0001  # natural death percent (per day)
B = 0.0095  # transmission percent  (per day)
G = 0.0001  # resurect percent (per day)
A = 0.0001  # destroy percent  (per day)

# solve the system dy/dt = f(y, t)
def f(y, t):
     Si = y[0]
     Zi = y[1]
     Ri = y[2]
     # the model equations (see Munz et al. 2009)
     f0 = P - B*Si*Zi - d*Si
     f1 = B*Si*Zi + G*Ri - A*Si*Zi
     f2 = d*Si + A*Si*Zi - G*Ri
     return [f0, f1, f2]

# initial conditions
S0 = 500.             # initial population
Z0 = 30                 # initial zombie population
R0 = 60                 # initial death population
y0 = [S0, Z0, R0]     # initial condition vector

#looping over some time instead of integrating in one go.
t_a = 0 
oput = 500
t_b = t_a + oput
delta_t = t_a + 100 
tend = 1000

while t_a < tend: 
    t_c = t_a + delta_t 
    t=[t_a,t_c]
    y = odeint(f,y0,t,mxstep=10000) #Integrator
    t_a = t_c

    if(t_a > oput):
        t_b = t_b +oput

        S = y[:,0]
        R = y[:,1]
        Z = y[:,2]


        g = pd.DataFrame({'Z': Z,'R': R})
        g.to_csv('example',mode='a',sep = '\t',index=False)

将无缝数据输出到文件而不是成对数据的最佳方式是什么?你知道吗


Tags: 文件数据import时间pltscipyinitialpopulation
1条回答
网友
1楼 · 发布于 2024-04-26 15:06:27

所以,输出并不是我认为你想要的,但这超出了你的问题范围。这会修正你的输出。你知道吗

dfs=[]
while t_a < tend: 
    t_c = t_a + delta_t 
    t=[t_a,t_c]
    y = odeint(f,y0,t,mxstep=10000) #Integrator
    t_a = t_c

    if(t_a > oput):
        t_b = t_b +oput

        S = y[:,0]
        R = y[:,1]
        Z = y[:,2]


        dfs.append(pd.DataFrame({'Z': Z,'R': R}))
#         g.to_csv('example.csv',mode='a',sep = '\t',index=False)
g=pd.concat(dfs,axis=0)
g.drop_duplicates().to_csv('example.csv',mode='a',sep = '\t',index=False)

相关问题 更多 >