我有一个包含多列成对的数据框:如果一列是值,那么相邻的列就是相应的计数。我想绘制一个直方图,使用值作为 x 变量并计数为 频率。
例如,我有以下列:
Age Counts
60 1204
45 700
21 400
. .
. .
34 56
10 150
我希望我的代码将 Age
值以十年为间隔在最大值和最小值之间进行分类,并从 Counts
列中获取每个间隔的累积频率,并且然后绘制直方图。有没有办法使用 matplotlib 来做到这一点?
我已经尝试了以下但徒劳无功:
patient_dets.plot(x='PatientAge', y='PatientAgecounts', kind='hist')
(patient_dets 是以 'PatientAge' 和 'PatientAgecounts' 为列的数据框)
最佳答案
我想你需要Series.plot.bar
:
patient_dets.set_index('PatientAge')['PatientAgecounts'].plot.bar()
如果需要垃圾箱,一种可能的解决方案是使用 pd.cut
:
#helper df with min and max ages
df1 = pd.DataFrame({'G':['14 yo and younger','15-19','20-24','25-29','30-34',
'35-39','40-44','45-49','50-54','55-59','60-64','65+'],
'Min':[0, 15,20,25,30,35,40,45,50,55,60,65],
'Max':[14,19,24,29,34,39,44,49,54,59,64,120]})
print (df1)
G Max Min
0 14 yo and younger 14 0
1 15-19 19 15
2 20-24 24 20
3 25-29 29 25
4 30-34 34 30
5 35-39 39 35
6 40-44 44 40
7 45-49 49 45
8 50-54 54 50
9 55-59 59 55
10 60-64 64 60
11 65+ 120 65
cutoff = np.hstack([np.array(df1.Min[0]), df1.Max.values])
labels = df1.G.values
patient_dets['Groups'] = pd.cut(patient_dets.PatientAge, bins=cutoff, labels=labels, right=True, include_lowest=True)
print (patient_dets)
PatientAge PatientAgecounts Groups
0 60 1204 60-64
1 45 700 45-49
2 21 400 20-24
3 34 56 30-34
4 10 150 14 yo and younger
patient_dets.groupby(['PatientAge','Groups'])['PatientAgecounts'].sum().plot.bar()
关于python - 使用 python 数据框中的两列(值、计数)绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41675931/