[英]apply numpy.histogram to multidimensional array
我想将numpy.histogram()
应用于沿轴的多维数组。
举例来说,我有一个2D数组,并且我想沿axis=1
应用histogram()
。
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]]
如何获得预期的输出?
我试图使用建议的解决方案这个职位 ,但是它没有得到我预期的输出。
对于np.histogram2d
情况,您可以通过创建虚拟x轴( i
)来使用np.histogram2d
做到这一点:
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. ]))
对于任意轴上的直方图,您可能需要使用np.meshgrid
和np.ravel_multi_axis
创建i
,然后使用其重塑所得的直方图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.