matlab - 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 相同的结果?
解决方案
根据 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)
推荐阅读
- angular - 如何将 .angular-cli.json 中的样式 .css 文件添加到业力单元测试中
- javascript - ng test --code-coverage 不打印覆盖率详细信息
- php - 具有简单 dom 的 scavage 网站需要很长时间,需要帮助或其他解决方案
- c# - NHibernate分页一对多关系属性
- android - 关于安卓工作室
- vb.net - 在 CefSharp 中修改 Cookie 的过期数据
- android - 模拟规则 - 允许访问;Android - 访问被拒绝
- selenium - 初始化 WebDriver Chrome 时出错,导致无法等待扩展背景加载
- swift - 使用codingkeys快速制作XML
- ionic3 - Ionic StreamingMedia 视频播放器导致状态栏在标题上重叠