在python数据帧中使用两列(值、计数)绘制直方图
我有一个数据帧,它有多个成对的列:如果一列是值,那么相邻的列就是相应的计数。我想用x变量的值绘制直方图,并将其计数为频率 例如,我有以下列:在python数据帧中使用两列(值、计数)绘制直方图,python,pandas,matplotlib,plot,histogram,Python,Pandas,Matplotlib,Plot,Histogram,我有一个数据帧,它有多个成对的列:如果一列是值,那么相邻的列就是相应的计数。我想用x变量的值绘制直方图,并将其计数为频率 例如,我有以下列: Age Counts 60 1204 45 700 21 400 . . . . 34 56 10 150 我希望我的代码以十年的间隔将年龄值存储在最大值和最小值之间,并从计数列中获取每个间隔的累积频率,然后绘制直方图。有没有办
Age Counts
60 1204
45 700
21 400
. .
. .
34 56
10 150
我希望我的代码以十年的间隔将年龄
值存储在最大值和最小值之间,并从计数
列中获取每个间隔的累积频率,然后绘制直方图。有没有办法使用matplotlib来实现这一点
我尝试过以下方法,但徒劳无功:
patient_dets.plot(x='PatientAge', y='PatientAgecounts', kind='hist')
(patient_dets是以“PatientAge”和“PatientAgecounts”作为列的数据框)我认为您需要:
如果需要垃圾箱,一种可能的解决方案是:
您可以使用pd.cut()来存储数据,然后使用函数plot('bar')进行绘图
您想要什么
Age
垃圾箱?您希望每个bin的频率是多少?我希望在最大值和最小值之间的十年间隔内对PatientAge
列进行bin。我希望频率来自每个间隔的patientagecocounts
列。
patient_dets.set_index('PatientAge')['PatientAgecounts'].plot.bar()
#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()
import numpy as np
nBins = 10
my_bins = np.linspace(patient_dets.Age.min(),patient_dets.Age.max(),nBins)
patient_dets.groupby(pd.cut(patient_dets.Age, bins =nBins)).sum()['Counts'].plot('bar')