求中值

时间:2014-10-09 15:08:39

标签: python dictionary median

我有一个数据集,它是基因节点的数据集。它有一对节点,它们是一些重量给定的值。我必须找到相应基因对的中位数。我计算节点对在整个数据集中出现的次数,然后计算该值的中值。这里Col[0] and Col[1]是节点对,Col[2]是权重。下面的代码打印节点和奇数出现的中间值是正确的,但是对于偶数出现,它显示两个中间值的较大值。任何建议赞赏。

输入类型:大文件中的小列表。

5372 937 65.0
4821 937 65.0
4376 937 65.0
2684 937 65.0
4391 3715 1880.0
3436 1174 2383.0
3436 3031 2383.0
3436 1349 2383.0
5372 937 70.0
4821 937 70.0
4376 937 70.0
2684 937 70.0
3826 896 10.0
3826 896 17.0
5372 937 62.0
4821 937 62.0
4376 937 62.0
2684 937 62.0
3826 896 50.0
4944 3715 482.0
4944 4391 482.0
2539 1431 323.0
5372 937 59.0
4821 937 59.0
4376 937 59.0
2684 937 59.0
896 606 11.0
3826 896 10.0
5045 4901 11.0
4921 4901 11.0
4901 3545 11.0
4901 3140 11.0
4901 4243 11.0

代码:

from collections import defaultdict
import numpy as np

pt  = defaultdict(float)
pm  = defaultdict(float)
pc  = defaultdict(int)
with open('input.txt', 'r') as f:
    with open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        pair = line[0], line[1]
        pc[pair] += 1       
        pt[pair] = float(line[2])
        pm[pair] = np.median(pt[pair])
        print pair, pc[pair], pm[pair]

根据定义,偶数组的中位数是两个中间数的平均值,对于奇数组,中间值是中位数。如果有一组数字,我怎样才能获得更好的中值?

1 个答案:

答案 0 :(得分:0)

您的pt词典不对。您正在存储每对的最后一个权重,并计算您需要整个权重列表的中位数。你可以这样做:

from collections import defaultdict
import numpy as np

pt  = defaultdict(list)
pc  = defaultdict(int)
with open('input.txt', 'r') as f:
    with open('output.txt', 'w') as o:
    for numline, line in enumerate((line.split() for line in f), start=1):
        pair = line[0], line[1]
        pc[pair] += 1       
        pt[pair].append(float(line[2]))

# now with the medians
pm  = dict()
for pair, weights in pt.items():
    pm[pair] = np.median(weights)
    print pair, pc[pair], pm[pair]