查找时间戳的平均值

2024-04-19 11:35:27 发布

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

我有一个3列的数据,我正在计算Col[0]Col[1]的成对出现率,并将Col[2]中对应于Col[0]Col[1]对的值相加。我可以很好地找到这些东西,但我也在尝试计算Col[3]中对应于Col[0]Col[1]的值的平均值。但是当我计算平均值时,我得到所有值的平均值,并且相同的值显示为永久值。有什么建议我该改什么?你知道吗

输入文件:

3545 3140 51.0
4602 183 2280.0
3545 3140 16.0
4945 3545 333.0
4945 3545 274.0
4391 2814 16.0
4945 3545 386.0
5045 4921 63078.0
5045 3545 896.0
4921 3545 896.0
5045 1683 1108.0
4921 1683 1108.0
5454 4391 4161.0
5454 5070 2755.0
5070 4391 2935.0

代码:

from collections import defaultdict
paircount = defaultdict(int)
pairtime = defaultdict(float)
pairper = defaultdict(float)
timeavg = defaultdict(float)


#get number of pair occurrences and total time
with open('input.txt', 'r') as f, open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        pair = line[0], line[1]
        paircount[pair] += 1
        pairtime[pair] += float(line[2])
    timeavg = pairtime[pair]/numline
    #pairper = dict((pair, c * 100.0 / numline) for (pair, c) in paircount.iteritems())
    for pair, freq in paircount.iteritems():
        #print pair[0], pair[1], c, pairper[pair], pairtime[pair]
        o.write("%s %s %s %s %s \n" % (pair[0], pair[1], freq, pairtime[pair], timeavg))
print 'done'

输出

col[0] col[1] freq[2] sum[3] avg[4]
785 607 3 7736.0 0.019245523048 
3489 2728 6 63616.0 0.019245523048 
1346 1295 1 422.0 0.019245523048 
4608 1136 2 2198.0 0.019245523048 
3893 2759 1 494.0 0.019245523048 
3530 2282 26 42882.0 0.019245523048 
3350 2542 2 10404.0 0.019245523048 
2655 1411 10 10842.0 0.019245523048 
4212 1613 13 53487.0 0.019245523048 
4503 656 7 4753.0 0.019245523048 
2105 674 1 2584.0 0.019245523048 
5139 1086 1 1488.0 0.019245523048 
3690 2034 6 3319.0 0.019245523048 
3867 1982 1 1134.0 0.019245523048 
4253 282 29 588893.0 0.019245523048

Tags: inforlinecolopenfloat平均值freq
1条回答
网友
1楼 · 发布于 2024-04-19 11:35:27

您希望计算每对的平均值,因此必须将timeavg计算放入第二个循环:

from collections import defaultdict
paircount = defaultdict(int)
pairtime = defaultdict(float)
pairper = defaultdict(float)
timeavg = defaultdict(float)


#get number of pair occurrences and total time
with open('input.txt', 'r') as f, open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        pair = line[0], line[1]
        paircount[pair] += 1
        pairtime[pair] += float(line[2])

    for pair, freq in paircount.iteritems():
        timeavg = pairtime[pair] / freq
        o.write("%s %s %s %s %s \n" % (pair[0], pair[1], freq, pairtime[pair], timeavg))

print 'done'

现在输出为:

4945 3545 3 993.0 331.0 
4602 183 1 2280.0 2280.0 
4391 2814 1 16.0 16.0 
5045 3545 1 896.0 896.0 
4921 1683 1 1108.0 1108.0 
5454 5070 1 2755.0 2755.0 
3545 3140 2 67.0 33.5 
4921 3545 1 896.0 896.0 
5045 4921 1 63078.0 63078.0 
5070 4391 1 2935.0 2935.0 
5454 4391 1 4161.0 4161.0 
5045 1683 1 1108.0 1108.0 

相关问题 更多 >