2

我有一些真实的降雨数据记录为日期和时间,以及翻斗式雨量计上的累计提示数。翻斗代表 0.5 毫米的降雨量。我想循环浏览文件并确定强度的变化(降雨/时间)所以我需要多个固定时间范围内的滚动平均值:所以我想累积降雨,直到累积 5 分钟的降雨并确定以 mm/ 为单位的强度小时。因此,如果在 5 分钟内记录 3 毫米,则等于 3/5*60 = 36 毫米/小时。10 分钟内相同的降雨量将是 18 毫米/小时...

因此,如果我有几个小时的降雨,我可能需要按几个标准时间间隔进行检查,例如:5、10、15、20、25、30、45、60 分钟等......此外,数据也会以相反的顺序记录在原始文件,所以最早的时间是在文件的末尾,后面和最后一个时间步首先出现在标题之后:看起来像......(这里 975 - 961 = 14 个提示 = 7mm 降雨)平均强度 1.4mm/ hr 但在 16:27 和 16:34 之间 967-961 = 6 个提示 = 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

有什么建议么?

4

2 回答 2

1

我不完全确定你有什么问题。

你知道如何读出文件吗?您可以执行以下操作:

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-28T11:21:11.227 回答
0

由于时间戳不是定期出现的,因此您应该使用插值来获得最准确的结果。这也将使滚动平均值更容易。我在下面的代码中使用这个答案Interpolate中的类。

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

下面我以 10 分钟的间隔打印前一小时每小时的提示数:

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一个 int 并创建了rolling_avg生成器。

于 2011-11-28T11:40:34.997 回答