【问题标题】:Numpy: use bins with infinite rangeNumpy:使用无限范围的垃圾箱
【发布时间】:2012-07-22 22:46:05
【问题描述】:

在我的 Python 脚本中,我有要装箱的浮点数。现在我在做:

min_val = 0.0
max_val = 1.0
num_bins = 20
my_bins = numpy.linspace(min_val, max_val, num_bins)
hist,my_bins = numpy.histogram(myValues, bins=my_bins)

但现在我想再添加两个 bin 来说明 1.0 的值。因此,一个 bin 应包含 (-inf, 0) 中的所有值,另一个 bin 应包含 [1, inf) 中的所有值

在使用 numpy 的 histogram 函数的同时,有什么直接的方法吗?

【问题讨论】:

    标签: python numpy range infinite bin


    【解决方案1】:

    您可以将numpy.inf 指定为上限,将-numpy.inf 指定为下限。

    【讨论】:

      【解决方案2】:

      函数numpy.histogram() 很高兴地接受bins 参数中的无限值:

      numpy.histogram(my_values, bins=numpy.r_[-numpy.inf, my_bins, numpy.inf])
      

      或者,您可以使用numpy.searchsorted()numpy.bincount() 的组合,尽管我认为这种方法没有太大优势。

      【讨论】:

        【解决方案3】:

        在 Numpy 1.16 版中,您拥有histogram_bin_edges。有了这个,今天的解决方案调用 histogram_bin_edges 来获取垃圾箱,concatenate -inf 和 +inf 并将其作为垃圾箱传递给 histogram

        a=[1,2,3,4,2,3,4,7,4,6,7,5,4,3,2,3]
        np.histogram(a, bins=np.concatenate(([np.NINF], np.histogram_bin_edges(a), [np.PINF])))
        

        结果:

        (array([0, 1, 3, 0, 4, 0, 4, 1, 0, 1, 0, 2]),
        array([-inf,  1. ,  1.6,  2.2,  2.8,  3.4,  4. ,  4.6,  5.2,  5.8,  6.4, 7. ,  inf]))
        

        如果您希望最后一个 bin 为空(就像我一样),您可以使用 range 参数并将一个小数字添加到 max

        a=[1,2,3,4,2,3,4,7,4,6,7,5,4,3,2,3]
        np.histogram(a, bins=np.concatenate(([np.NINF], np.histogram_bin_edges(a, range=(np.min(a), np.max(a)+.1)), [np.PINF])))
        

        结果:

        (array([0, 1, 3, 0, 4, 4, 0, 1, 0, 1, 2, 0]),
        array([-inf, 1.  , 1.61, 2.22, 2.83, 3.44, 4.05, 4.66, 5.27, 5.88, 6.49, 7.1 ,  inf]))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-11-06
          • 2021-04-20
          • 1970-01-01
          • 1970-01-01
          • 2011-10-22
          • 2016-05-22
          • 1970-01-01
          相关资源
          最近更新 更多