【发布时间】:2019-04-02 19:19:01
【问题描述】:
我很好奇是否可以计算直方图中特定 bin 的元素数量,即 0-10 范围内的所有元素
你会怎么做?
例如plt.hist(数据, bins=[0, 10, 20, 30, 40, 50, 100]) 是否可以计算数据集中进入 bin 0-10 的所有元素
【问题讨论】:
标签: python matplotlib histogram
我很好奇是否可以计算直方图中特定 bin 的元素数量,即 0-10 范围内的所有元素
你会怎么做?
例如plt.hist(数据, bins=[0, 10, 20, 30, 40, 50, 100]) 是否可以计算数据集中进入 bin 0-10 的所有元素
【问题讨论】:
标签: python matplotlib histogram
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
【讨论】:
print(counts[0])。
是的,pd.Series.value_counts 有 bins 参数。
import pandas as pd
s = pd.Series(np.random.randint(0,100,50))
s.value_counts(bins=[0,10,20,30,40,50,60,70,80,90,100]).sort_index()
输出:
(-0.001, 10.0] 8
(10.0, 20.0] 6
(20.0, 30.0] 5
(30.0, 40.0] 6
(40.0, 50.0] 2
(50.0, 60.0] 3
(60.0, 70.0] 4
(70.0, 80.0] 3
(80.0, 90.0] 6
(90.0, 100.0] 7
dtype: int64
【讨论】:
pandas。这很简单。只需在最后一个 bin 上正确设置边界即可。
pandas 答案(我不使用 matplotlib,但使用 pandas :))。所以是的,OP 的需求可以通过他们使用的原始库来满足,但是关于 SO 的问题也面向公众:D