首页 > 解决方案 > 计算特定 bin 中的元素数

问题描述

我很好奇是否可以计算直方图中特定 bin 的元素数量,即 0-10 范围内的所有元素

你会怎么做?

例如 plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100]) 是否可以计算数据集中进入 bin 0-10 的所有元素

标签: pythonmatplotlibhistogram

解决方案


Matplotlib 直方图返回每个 bin 的计数:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(0, 100, 1000)

counts, edges, plot = plt.hist(x, bins=[0, 10, 20, 50, 100])
print(counts)
print(counts[0]) # first bin

推荐阅读