python - 使用 python 数据框中的两列(值、计数)绘制直方图

标签 python pandas matplotlib plot histogram

我有一个包含多列成对的数据框:如果一列是值,那么相邻的列就是相应的计数。我想绘制一个直方图,使用值作为 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()

graph

如果需要垃圾箱,一种可能的解决方案是使用 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()

graph1

关于python - 使用 python 数据框中的两列(值、计数)绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41675931/

相关文章:

Python ISO 日期时间包含 'T' 字符

python - 如何在 Python 的另一个函数中找出特定函数参数的默认值?

python - Pandas 切片系列

python - Python中抽象类和接口(interface)的区别

java - 为什么 java/javascript/python 强制在方法名称后使用 (),即使它不带参数?

python - pandas csv到行和列的数据框转换

python - 通过取消列出值并保留索引来构建 pandas 数据框

python - 如何配置y轴以减少零并节省空间?

python - 在 imshow 上绘制 RGB 点

ubuntu - Matplotlib + Ubuntu + GTK3 未显示绘图