Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将numpy.histogram应用于多维数组_Python_Python 3.x_Numpy_Multidimensional Array_Histogram - Fatal编程技术网

Python 将numpy.histogram应用于多维数组

Python 将numpy.histogram应用于多维数组,python,python-3.x,numpy,multidimensional-array,histogram,Python,Python 3.x,Numpy,Multidimensional Array,Histogram,我想将numpy.histogram()应用于沿轴的多维数组 例如,我有一个2D数组,我想沿着轴=1应用直方图() 代码: 输出: 预期产出: 如何获得预期的输出 我尝试使用中建议的解决方案,但没有达到预期的输出。对于n-d情况,您可以使用np.historogram2d只需制作一个虚拟x轴(I): 输出 vec_hist(array, bins) Out[453]: (array([[ 1., 1., 0., 2., 1.], [ 1., 1., 1., 2.,

我想将
numpy.histogram()
应用于沿轴的多维数组

例如,我有一个2D数组,我想沿着轴=1应用
直方图()

代码: 输出: 预期产出: 如何获得预期的输出


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

对于n-d情况,您可以使用
np.historogram2d
只需制作一个虚拟x轴(
I
):

输出

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\u多轴创建
i
,然后使用它来重塑生成的直方图。

对于n-d情况,您可以使用
np.histogram2d
只需制作一个虚拟x轴(
i
):

输出

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\u多轴
创建
i
,然后使用它来重塑生成的直方图。

谢谢您的回答。我很感激。你能给我举一个n维数组的例子吗?您的解决方案适用于2d情况。将其扩展为n-d,但仅当直方图位于最后一个轴上时才有效。在任意轴上实现将需要更多的工作。你能给我一个例子吗?在我的例子中,我需要在最后一个轴上应用直方图。修复了一些错误,希望现在可以用于多维。谢谢你的回答。我很感激。你能给我举一个n维数组的例子吗?您的解决方案适用于2d情况。将其扩展为n-d,但仅当直方图位于最后一个轴上时才有效。在任意轴上实现将需要更多的工作。你能给我一个例子吗?在我的例子中,我需要在最后一个轴上应用直方图。修复了一些错误,希望现在可以用于多维。您可以按照本文的建议使用
apply_沿线
。您可以按照本文的建议使用
apply_沿线
[[1 1 0 2 1],
 [1 1 1 2 0],
 [1 1 2 0 1]]
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.       ]))