如何为直方图创建频率数据?

2024-04-16 13:13:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在导入一个只有一列数据的excel文件,并希望创建一个直方图。我希望x轴是数据本身,y轴是数据的频率

如何创建统计数据频率的词典

我知道我需要创建两个词典:

x = The data from the excel file 
y = [] what goes here? 

2条回答

如果您有这样的输入:

x_orig=[1993, 1998, 1999, 1997, 1996, 1993, 1995, 1996]

最有效和可扩展的方法是为y使用库collections,并创建一组x_orig以避免重复:

from collections import Counter

y=Counter(x_orig)
x=set(x_orig)

结果:

x={1993, 1995, 1996, 1997, 1998, 1999}
y=Counter({1993: 2, 1998: 1, 1999: 1, 1997: 1, 1996: 2, 1995: 1})

然后,您可以轻松地绘制这两个变量

没有理由重新发明轮子。Numpy提供了此项目所需的工具

import numpy as np 

my_column = np.random.random(20) # this is the column you load from Excel
my_bins = np.linspace(0,1,num=5) # 4 bins in your histogram      
my_hist = np.histogram(my_column,bins = my_bins) 
print (my_hist[0]) # this is your freqency distribution

输出:

[6 4 5 5]

相关问题 更多 >