【问题标题】:Binning of data along one axis in numpy在numpy中沿一个轴对数据进行分箱
【发布时间】:2017-02-22 09:47:25
【问题描述】:

我有一个大型二维数组arr,我想使用 numpy 在第二个轴上装箱。因为np.histogram 将我当前使用的 for 循环的数组展平:

import numpy as np

arr = np.random.randn(100, 100)

nbins = 10
binned = np.empty((arr.shape[0], nbins))

for i in range(arr.shape[0]):
    binned[i,:] = np.histogram(arr[i,:], bins=nbins)[0]

我觉得在 numpy 中应该有一种更直接、更有效的方法来做到这一点,但我没有找到。

【问题讨论】:

    标签: python numpy histogram binning


    【解决方案1】:

    我对 Ami 解决方案中的 lambda 有点困惑,所以我将其展开以显示它在做什么:

    def hist_1d(a):
        return np.histogram(a, bins=bins)[0]
    
    counts = np.apply_along_axis(hist_1d, axis=1, arr=x)
    

    【讨论】:

      【解决方案2】:

      您必须使用专门针对您的问题的numpy.histogramdd

      【讨论】:

      • 我不太明白怎么做。我的理解是histogramdd 是为创建多维直方图而构建的,但我想获得几个一维直方图。
      【解决方案3】:

      你可以使用np.apply_along_axis:

      x = np.array([range(20), range(1, 21), range(2, 22)])
      
      nbins = 2
      >>> np.apply_along_axis(lambda a: np.histogram(a, bins=nbins)[0], 1, x)
      array([[10, 10],
             [10, 10],
             [10, 10]])
      

      主要优点(如果有的话)是它稍微短一些,但我不希望有太多的性能提升。在组装每行结果时,它的效率可能会稍微高一些。

      【讨论】:

      • 只是指出使用lambda a:[0] 而不仅仅是np.apply_along_axis(np.histogram, axis=1, arr=x, bins=bins) 的原因是因为np.histogram 返回两个输出,histbin_edges,在这里我们只想要hist
      猜你喜欢
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2020-08-16
      相关资源
      最近更新 更多