首页 > 解决方案 > Numpy 相当于 MATLAB 的 hist

问题描述

由于某种原因,Numpy 的 hist 总是返回比 MATLAB 的 hist 少一个 bin:

例如在 MATLAB 中:

x = [1,2,2,2,1,4,4,2,3,3,3,3];
[Rep,Val] = hist(x,unique(x));

给出:

Rep = [2 4 4 2]
Val = [1 2 3 4]

但在 Numpy 中:

import numpy as np
x = np.array([1,2,2,2,1,4,4,2,3,3,3,3])
Rep, Val = np.histogram(x,np.unique(x))

给出:

>>>Rep
array([2, 4, 6])
>>>Val
array([1, 2, 3, 4])

如何获得与 MATLAB 相同的结果?

标签: matlabnumpy

解决方案


根据 dilayapici 在这篇文章中的回答,以np.histogram与 Matlab 相同的方式运行 Python 的通用解决方案(适用于您的示例)hist如下:

x = np.array([1,2,2,2,1,4,4,2,3,3,3,3])
# Convert the bin centers given in Matlab to bin edges needed in Python.
numBins = len(np.unique(x))
bins = np.linspace(np.amin(x), np.amax(x), numBins)
# Edit the 'bins' argument of `np.histogram` by just putting '+inf' as the last element.
bins = np.concatenate((bins, [np.inf]))
Rep, Val = np.histogram(x, bins)

输出:

Rep
array([2, 4, 4, 2], dtype=int64)

推荐阅读