我有一些真实的降雨数据记录为日期和时间,以及倾倒桶雨量计上累积的小费数量。倾倒桶代表0.5毫米的降雨量。我希望循环浏览文件并确定强度(降雨量/时间)的变化,因此我需要多个固定时间范围内的滚动平均值:因此,我希望累积降雨量,直到累积了5分钟的降雨量,并以毫米/小时为单位确定强度。因此,如果在5分钟内记录3 3mm,则等于3/5*60 =36 3mm/小时。同样的降雨量在10分钟内为18毫米/小时。
因此,如果我有几个小时的降雨,我可能需要以几个标准间隔进行复习,比如: 5,10,15,20,25,30,45,60分钟等等。此外,原始文件中的数据是以相反的顺序记录的,因此最早的时间在文件的末尾,较晚的和最后的时间步长首先出现在标题之后:看起来像...(这里975 - 961 = 14个tips =7毫米降雨量)平均强度1.4毫米/小时,但在16:27到16:27之间:34 967-961 =6个tips =3毫米,7分钟=27.71毫米/小时
7424 Figtree (O'Briens Rd)
DATE :hh:mm Accum Tips
8/11/2011 20:33 975
8/11/2011 20:14 974
8/11/2011 20:04 973
8/11/2011 20:00 972
8/11/2011 19:35 971
8/11/2011 18:29 969
8/11/2011 16:44 968
8/11/2011 16:34 967
8/11/2011 16:33 966
8/11/2011 16:32 965
8/11/2011 16:28 963
8/11/2011 16:27 962
8/11/2011 15:30 961
有什么建议吗?
发布于 2011-11-28 19:21:11
我不完全确定你有什么问题。
你知道怎么把文件读出来吗?你可以这样做:
data = [] # Empty list of counts
# Skip the header
lines = [line.strip() for line in open('data.txt')][2::]
for line in lines:
print line
date, hour, count = line.split()
h,m = hour.split(':')
t = int(h) * 60 + int(m) # Compute total minutes
data.append( (t, int(count) ) ) # Append as tuple
data.reverse()
因为你的数据是累积性的,所以你需要减去每两个条目,这就是python的列表理解非常好的地方。
data = [(t1, d2 - d1) for ((t1,d1), (t2, d2)) in zip(data, data[1:])]
print data
现在,我们需要遍历并查看在过去x分钟内有多少条目。
timewindow = 10
for i, (t, count) in enumerate(data):
# Find the entries that happened within the last [...] minutes
withinwindow = filter( lambda x: x[0] > t - timewindow, data )
# now you can print out any kind of stats about this "within window" entries
print sum( count for (t, count) in withinwindow )
发布于 2011-11-28 19:40:35
由于时间戳不是以规则的间隔出现的,因此应使用插值来获得最准确的结果。这也将使滚动平均值变得更容易。
from time import strptime, mktime
totime = lambda x: int(mktime(strptime(x, "%d/%m/%Y %H:%M")))
with open("my_file.txt", "r") as myfile:
# Skip header
for line in myfile:
if line.startswith("DATE"):
break
times = []
values = []
for line in myfile:
date, time, value = line.split()
times.append(totime(" ".join((date, time))))
values.append(int(value))
times.reverse()
values.reverse()
i = Interpolate(times, values)
现在只需要选择间隔并计算每个间隔的端点之间的差异。让我们为此创建一个生成器函数:
def rolling_avg(cumulative_lookup, start, stop, step_size, window_size):
for t in range(start + window_size, stop, step_size):
total = cumulative_lookup[t] - cumulative_lookup[t - window_size]
yield total / window_size
start = totime("8/11/2011 15:30")
stop = totime("8/11/2011 20:33")
for avg in rolling_avg(i, start, stop, 600, 3600):
print avg * 3600
编辑:让totime
返回一个整数,并创建了rolling_avg
生成器。
https://stackoverflow.com/questions/8294602
复制相似问题