NumPy教程-numpy.histogram()在Python中的使用
语法:
numpy.histogram(x, bins=10, range=None, normed=None, weights=None, density=None)
参数:
👉点击领取:最全Python资料合集
返回值:
示例1:
import numpy as npa=np.histogram([1, 5, 2], bins=[0, 1, 2, 3])a
输出:
(array([0, 1, 1], dtype=int64), array([0, 1, 2, 3]))
在上面的代码中:
我们导入了别名为np的numpy。
我们声明了变量'a',并赋值为np.histogram()函数的返回值。
我们在函数中传递了一个数组和bin的值。
最后,我们尝试打印'a'的值。
示例2:
import numpy as npx=np.histogram(np.arange(6), bins=np.arange(7), density=True)x
输出:
(array([0.16666667, 0.16666667, 0.16666667, 0.16666667, 0.16666667,0.16666667]), array([0, 1, 2, 3, 4, 5, 6]))
示例3:
import numpy as npx=np.histogram([[1, 3, 1], [1, 3, 1]], bins=[0,1,2,3])x
输出:
(array([0, 4, 2], dtype=int64), array([0, 1, 2, 3]))
示例4:
import numpy as npa = np.arange(8)hist, bin_edges = np.histogram(a, density=True)histbin_edges
输出:
array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143,0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143])array([0. , 0.7, 1.4, 2.1, 2.8, 3.5, 4.2, 4.9, 5.6, 6.3, 7. ])
示例5:
import numpy as npa = np.arange(8)hist, bin_edges = np.histogram(a, density=True)histhist.sum()np.sum(hist * np.diff(bin_edges))
输出:
array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143,0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143])1.42857142857142881.0
在上面的代码中:
我们导入了别名为np的numpy。
我们使用np.arange()函数创建了一个数组'a'。
我们声明了变量'hist'和'bin_edges',然后将np.histogram()函数的返回值赋值给它们。
我们在函数中传递了数组'a',并在函数中将'density'设置为True。
我们尝试打印'hist'的值。
最后,我们尝试使用hist.sum()和np.sum()计算直方图值的总和,其中我们传递了直方图值和箱的边缘。
输出中显示了一个包含直方图值和直方图值总和的ndarray。
热门推荐