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

时间:2018-07-27 16:11:15

标签: python pandas scipy differential-equations odeint

我试图集成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)

将无缝数据输出到文件而不是成对数据的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

因此,输出结果并非我想的完全一样,但这超出了您的问题范围。这应该可以修复您的输出。

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)