簡體   English   中英

將numpy.histogram應用於多維數組

[英]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.meshgridnp.ravel_multi_axis創建i ,然后使用其重塑所得的直方圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM