Numpy&熊猫:从熊猫直方图中返回直方图值?

时间:2016-07-19 06:53:06

标签: python numpy pandas matplotlib

我知道我可以用熊猫绘制直方图:

df4 = pd.DataFrame({'a': np.random.randn(1000) + 1})
df4['a'].hist()

enter image description here

但是如何从这样的情节中检索直方图计数呢?

我知道我可以通过(来自Histogram values of a Pandas Series

来做到这一点
count,division = np.histogram(df4['a'])

但是使用df.hist()之后得到计数值感觉非常多。是否可以直接从熊猫中获取频率值?

2 个答案:

答案 0 :(得分:12)

快速回答是:

pd.cut(df4['a'], 10).value_counts().sort_index()

来自documentation

bins: integer, default 10
Number of histogram bins to be used

请看pd.cut(df4['a'], 10).value_counts()

您会看到值与np.histogram

相同

答案 1 :(得分:0)

这是另一种计算熊猫直方图的方法。它更复杂,但IMO更好,因为您避免了pd.cut会返回破坏任何图的怪异字符串框。您还将获得使用.pipe()的样式点:

(df['a']
 .pipe(lambda s: pd.Series(np.histogram(s, range=(0, 100), bins=20)))
 .pipe(lambda s: pd.Series(s[0], index=s[1][:-1]))
)

然后您可以在管道上添加更多内容,例如:

.pipe(lambda s: s/s.sum())

这将为您提供分发。

理想情况下,density中有一个明智的pd.hist可以为您做到这一点。 Pandas确实有一个density=False关键字,但这毫无意义。我已经读过超过this one之类的解释,但我从未理解过它,也不了解谁会真正使用。在直方图中看到分数的99.9%的时间中,您认为是“分布”,而不是np.sum(pdf * np.diff(bins))实际计算的density=True。让你想哭。

相关问题