简体   繁体   English

在Python中取两个直方图的平均值

[英]taking the average of two histograms in python

I have two histograms (freq dist) and I want to take the average of the frequencies in each corresponding bin of the two histograms and get one histogram that displays the average frequencies. 我有两个直方图(freq dist),我想取两个直方图的每个对应bin中的频率平均值,然后得到一个显示平均频率的直方图。

Can I do this with pylab? 我可以用pylab做到吗?

a=[]
sites = [23,45,32,56,76,87,45,21,34,23,78,90,23,45,21,32,34,54,67,54,33,12,34]
import random
j=1
for i in range(1,len(sites)):
    r = random.choice([0,1])
    if r == 1:
        a.append(sites[i] - sites[i-j])
        j=1
    else:
        j+=1
import pylab
pylab.hist(a, bins=10)
pylab.title("hist")
pylab.xlabel("length")
pylab.ylabel("Count")
pylab.show()

the snippet code is run several times with different "sites" data to get a several histograms. 代码段代码会使用不同的“站点”数据运行几次,以获得多个直方图。 I want to "average" these histograms in to one. 我想将这些直方图平均化为一个。

This is unreasonable unless both histograms have the same total number of elements, otherwise you must take the weighted average. 除非两个直方图的元素总数相同,否则这是不合理的,否则您必须采用加权平均值。

To do so, assuming your histograms have the same frequency bins, do this if the histograms are list-like: 为此,假设您的直方图具有相同的频点,如果直方图类似于列表,请执行以下操作:

[(x1+x2)/2 for x1,x2 in zip(h1,h2)]

If the histograms are dict-like: 如果直方图类似于dict:

def mergeBins(bin1, bin2):
    label1,value1 = bin1
    label2,value2 = bin2
    assert label1==label2
    return label1, (value1+value2)/2

dict(mergeBins() in bin1,bin2 zip(h1.items(), h2.items()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM