如何生成随机时间序列数据,包括2月29天?

时间:2013-10-31 03:53:41

标签: python arrays date datetime

我使用以下代码生成1950年至2009年的随机降雨量数据,其中已知概率,平均值和标准差。但是,在闰年的29天里,我一直在苦苦挣扎。而且,我也试图将输出保存在文本文件中,但它会显示错误消息,如

  

TypeError:需要浮点参数,而不是numpy.string _

有人可以帮帮我吗?

我的代码:

import numpy as np
import random
import itertools
import datetime

dry =[0.33,0.27,0.32,0.41,0.42,0.45,0.57,0.52,0.45,0.39,0.37,0.37]
wet = [0.66,0.72,0.67,0.58,0.57,0.54,0.42,0.47,0.54,0.60,0.62,0.62]
d2d_tran = [0.56,0.50,0.58,0.62,0.63,0.67,0.73,0.66,0.60,0.56,0.57,0.62]
w2w_tran = [0.78,0.80,0.79,0.73,0.72,0.72,0.63,0.64,0.66,0.71,0.74,0.76]
mu = [3.71, 4.46, 4.11, 2.94, 3.00, 2.87, 2.31, 2.44, 2.56, 3.45, 4.32, 4.12]
sigma = [6.72,7.92,7.49,6.57,6.09,5.53,4.38,4.69,4.31,5.71,7.64,7.54]
days = [31,28,31,30,31,30,31,31,30,31,30,31]
rain = []

for y in xrange(0,60):
    for m in xrange(0,12):
        random_num = np.random.rand(days[m])
        if random.random() <= dry[m]:
            random_num[0] = 0
        else:
            r = abs(random.gauss(mu[m],sigma[m]))
            random_num[0] = r
        for i in xrange(1,days[m]):
            if random_num[i-1] == 0:
                if random_num[i] <= d2d_tran[m]:
                    random_num[i] = 0
                else:
                    r = abs(random.gauss(mu[m],sigma[m]))
                    random_num[i] = r
            else:
                if random_num[i] <= w2w_tran[m]:
                    r = abs(random.gauss(mu[m],sigma[m]))
                    random_num[i] = r
                else:
                    random_num[i] = 0
        rain.append(random_num)
rain_series = []
for j in itertools.chain.from_iterable(rain):
    rain_series.append(j)
y = np.array(rain_series).reshape(-1, 1) 

date_series = []
def generate_dates(start_date, end_date):
return (start_date + datetime.timedelta(days=d) for d in xrange((end_date - start_date).days + 1))
start_date = datetime.date(1950, 1, 1)
end_date = datetime.date(2009, 12, 16)
for current_date in generate_dates(start_date, end_date):
    f = current_date.strftime('%Y-%m-%d')
    date_series.append(f)
z = np.array(date_series).reshape(-1, 1)

#### Here I have 365x60 = 21900 rainfall values, that is why I had to 
####set the end_date upto (2009,12,16). If
#### the February days for leap years can be set as 29 in days[] of 
####rain_series than this problem would be solved.

data = np.concatenate((z,y), axis=1)
print data
data1 = data.reshape((21900,2))
np.savetxt('Random Rainfall Data.txt', data1)
#### I want to shape data in two columns like dates and rainfall.
#### And than, save it into a text file. But, it provides an error!!!

1 个答案:

答案 0 :(得分:0)

关于数据写入问题,您必须添加第三个参数。这取决于您的具体问题:

np.savetxt('test.txt', a, '%s') # Example

有关更多格式信息,请参阅documentation