在python datafram中使用两列(值、计数)绘制直方图

2024-09-29 00:14:30 发布

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

我有一个成对有多个列的数据帧:如果一列是值,那么相邻的列就是相应的计数。我想绘制一个柱状图,使用值作为变量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”为列的数据帧)


Tags: 数据代码age间隔绘制直方图频率计数
2条回答

可以使用pd.cut()将数据装箱,然后使用函数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')

我想你需要^{}

patient_dets.set_index('PatientAge')['PatientAgecounts'].plot.bar()

graph

如果需要箱子,一个可能的解决方案是使用^{}

#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()

graph1

相关问题 更多 >