【问题标题】:Saving a histogram after removing a bin in numpy在numpy中删除bin后保存直方图
【发布时间】:2016-06-12 14:14:41
【问题描述】:

我有大量数据,我需要获取没有最高频率的 bin 的直方图。我使用this 来删除这样的bin,但是我需要保存更改后的直方图,因为我必须将它与另一个直方图进行比较。我不知道该怎么做,因为初始数据没有改变,我只能在演示文稿中看到变化。我正在考虑以某种方式操纵初始数据以反映直方图中的这种变化(比如删除出现在 bin 中频率最高的那些数据),但到目前为止我尝试过的方法不起作用。这是一个示例代码,主要基于上面的链接,为了我的目的进行了一些更改,但不幸的是它并没有完成这项工作:

import numpy as np
import matplotlib.pyplot as plt

gaussian_numbers = np.random.randn(100)

# Get histogram
values, bin_edges = np.histogram(gaussian_numbers, bins=6)
centers = (bin_edges[:-1] + bin_edges[1:]) / 2
width = (bin_edges[1] - bin_edges[0])
plt.bar(centers, values, color="blue",align='center',width=width)
plt.show()

values[np.where(values == np.max(values))] = 0
binCenters =(bin_edges[:-1] + bin_edges[1:]) / 2

plt.bar(binCenters, values, color="blue",align='center', width=width)  
plt.show()

new=gaussian_numbers[(gaussian_numbers!= np.max(values))]
print np.sum(new-gaussian_numbers)

当我绘制条形图时,我可以看到频率最高的 bin 已被删除。但是,当我尝试从我的数据中删除这些值并将其保存在一个名为 new 的数组中时(然后我想保存 new 的直方图),new之间没有区别> 和 gaussian_numbers。这意味着它们的直方图也是相同的。有没有办法删除这些数据?

【问题讨论】:

    标签: python numpy histogram


    【解决方案1】:

    我想我知道该怎么做了。基本上,我找到直方图频率最高的 bin 范围,然后将其从原始数据中删除。下面是示例代码,感兴趣的朋友可以参考一下:

    import numpy as np
    import matplotlib.pyplot as plt
    
    gaussian_numbers = np.random.randn(100)
    print gaussian_numbers.shape
    # Get histogram
    values, bin_edges = np.histogram(gaussian_numbers, bins=6)
    centers = (bin_edges[:-1] + bin_edges[1:]) / 2
    width = (bin_edges[1] - bin_edges[0])
    plt.bar(centers, values, color="blue",align='center',width=width)
    plt.show()
    
    
    bin_min= bin_edges[np.where(values == np.max(values))]
    bin_max= bin_min +width
    new_val = gaussian_numbers[(gaussian_numbers<bin_min) | (gaussian_numbers>bin_max)]
    
    
    values, bin_edges = np.histogram(new_val, bins=6)
    
    centers = (bin_edges[:-1] + bin_edges[1:]) / 2
    width = (bin_edges[1] - bin_edges[0])
    plt.bar(centers, values, color="blue",align='center',width=width)
    plt.show()
    

    这是之前和之后的条形图:

    请注意,现在我可以保存新的直方图,因为我在删除初始直方图中的最高频率 bin 后保存了新数据。另外,请注意,初始和最终 bin 必须相等,才能观察已删除数据的 bin。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 2015-07-10
      • 1970-01-01
      相关资源
      最近更新 更多