将 numpy.histogram 应用于多维数组

问题描述 投票:0回答:2

我想将

numpy.histogram()
应用于沿轴的多维数组。

比如说,我有一个 2D 数组,我想沿着

histogram()
应用
axis=1

代码:

import numpy

array = numpy.array([[0.6, 0.7, -0.3, 1.0, -0.8], [0.2, -1.0, -0.5, 0.5, 0.8], 
                    [0.25, 0.3, -0.1, -0.8, 1.0]])
bins = [-1.0, -0.5, 0, 0.5, 1.0, 1.0]
hist, bin_edges = numpy.histogram(array, bins)
print(hist)

输出:

[3 3 3 4 2]

预期输出:

[[1 1 0 2 1],
 [1 1 1 2 0],
 [1 1 2 0 1]]

如何获得预期的输出?

我尝试使用这篇文章中建议的解决方案,但它没有让我达到预期的输出。

python python-3.x numpy multidimensional-array histogram
2个回答
0
投票

对于 n-d 情况,您可以通过制作虚拟 x 轴 (

np.histogram2d
) 来使用
i
来完成此操作:

def vec_hist(a, bins):
    i = np.repeat(np.arange(np.product(a.shape[:-1]), a.shape[-1]))
    return np.histogram2d(i, a.flatten(), (a.shape[0], bins)).reshape(a.shape[:-1], -1)

输出

vec_hist(array, bins)
Out[453]: 
(array([[ 1.,  1.,  0.,  2.,  1.],
        [ 1.,  1.,  1.,  2.,  0.],
        [ 1.,  1.,  2.,  0.,  1.]]),
 array([ 0.        ,  0.66666667,  1.33333333,  2.        ]),
 array([-1.       , -0.5      ,  0.       ,  0.5      ,  0.9999999,  1.       ]))

对于任意轴上的直方图,您可能需要使用

i
np.meshgrid
创建
np.ravel_multi_axis
,然后使用它来重塑生成的直方图。


0
投票

Numpy 代码已更改,Daniel F 提出的答案不再有效。 这是二维数组的简化版本:

def vec_hist(a, bins):
    i = np.tile(np.arange(a.shape[0]), (a.shape[1], 1)).T.flatten()
    H, _, _ = np.histogram2d(i, a.flatten(), (a.shape[0], bins))
    return H

所以基本上首先我们构建一个坐标“i”列表,它只是沿最后一个轴的数据索引。 然后我们将其与数据数组“a”一起展平,然后将其发送到 np.histogram2d。 histogram2d 的 bin 参数是虚拟的 bin 和实际所需的维度。

代码:

array = np.array([[0.6, 0.7, -0.3, 1.0, -0.8], 
                  [0.2, -1.0, -0.5, 0.5, 0.8], 
                  [0.25, 0.3, -0.1, -0.8, 1.0]])
bins = [-1.0, -0.5, 0, 0.5, 1.0, 1.0]
vec_hist(array, bins)

输出

array([[1., 1., 0., 2., 1.],
       [1., 1., 1., 2., 0.],
       [1., 1., 2., 0., 1.]])
© www.soinside.com 2019 - 2024. All rights reserved.