Python:发生的频率

时间:2014-03-02 12:51:36

标签: python matplotlib

我有整数列表,想要得到每个整数的频率。讨论了here

问题是当我的数据集只包含整数时,我使用的方法给出了浮点数的频率。为什么会发生这种情况以及如何从数据中获取整数频率?

我正在使用pyplot.histogram绘制出现频率的直方图

import numpy as np
import matplotlib.pyplot as plt
from numpy import *
data = loadtxt('data.txt',dtype=int,usecols=(4,)) #loading 5th column of csv file into array named data. 
plt.hist(data) #plotting the column as histogram 

我得到直方图,但我注意到如果我“打印”hist(数据)

hist=np.histogram(data)
print hist(data)

我明白了:

(array([ 2323, 16338,  1587,   212,    26,    14,     3,     2,     2,     2]), 
array([  1. ,   2.8,   4.6,   6.4,   8.2,  10. ,  11.8,  13.6,  15.4,
    17.2,  19. ]))

其中第二个数组表示值,第一个数组表示出现次数。

在我的数据集中,所有值都是整数,第二个数组是如何发生浮点数的,以及如何获得整数频率?

更新:

这解决了问题,谢谢Lev的回复。

plt.hist(data, bins=np.arange(data.min(), data.max()+1))

为了避免创建一个新问题,我如何为每个整数绘制“中间”列?比如说,我希望整数3的列占用2.5到3.5之间的空间而不是3到4之间的空间。

histogram

3 个答案:

答案 0 :(得分:15)

如果您未指定要使用的容器,np.histogrampyplot.hist将使用默认设置,即使用10个相等的容器。第一个bin的左边界是最小值,最后一个bin的右边界是最大值。

这就是bin边框是浮点数的原因。您可以使用bins关键字参数来强制执行另一个二进制选择,例如:

plt.hist(data, bins=np.arange(data.min(), data.max()+1))

编辑:将所有垃圾箱向左移动的最简单方法可能是从所有垃圾箱边框中减去0.5:

plt.hist(data, bins=np.arange(data.min(), data.max()+1)-0.5)

实现相同效果的另一种方法(如果存在非整数则不等效):

plt.hist(data, bins=np.arange(data.min(), data.max()+1), align='left')

答案 1 :(得分:1)

您可以使用How to count the frequency of the elements in a list?中讨论的groupby中的itertools

import numpy sa np
from itertools import groupby
freq = {key:len(list(group)) for key, group in groupby(np.sort(data))}

答案 2 :(得分:0)

(晚点,只是想我会添加一个seaborn实现)

上述问题的季节性实施:

seaborn.__version__ = 0.9.0在撰写本文时。

加载库并设置模拟数据。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

data = np.array([3]*10 + [5]*20 + [7]*5 + [9]*27 + [11]*2)

使用seaborn.distplot绘制数据:

使用根据上述问题计算得出的指定垃圾箱。

sns.distplot(data,bins=np.arange(data.min(), data.max()+1),kde=False,hist_kws={"align" : "left"})
plt.show()

尝试使用numpy内置的分箱方法

我在下面使用了doane分箱方法,该方法产生了整数分箱,值得从numpy.histogram_bin_edges中尝试standard binning methods,因为matplotlib.hist()就是这样对数据进行分箱的。

sns.distplot(data,bins="doane",kde=False,hist_kws={"align" : "left"})
plt.show()

产生以下直方图:

enter image description here