内容简介:翻译自:https://stackoverflow.com/questions/43005462/pandas-bar-plot-with-binned-range
有没有办法从连续数据分组到预定义的间隔创建条形图?例如,
In[1]: df Out[1]: 0 0.729630 1 0.699620 2 0.710526 3 0.000000 4 0.831325 5 0.945312 6 0.665428 7 0.871845 8 0.848148 9 0.262500 10 0.694030 11 0.503759 12 0.985437 13 0.576271 14 0.819742 15 0.957627 16 0.814394 17 0.944649 18 0.911111 19 0.113333 20 0.585821 21 0.930131 22 0.347222 23 0.000000 24 0.987805 25 0.950570 26 0.341317 27 0.192771 28 0.320988 29 0.513834 231 0.342541 232 0.866279 233 0.900000 234 0.615385 235 0.880597 236 0.620690 237 0.984375 238 0.171429 239 0.792683 240 0.344828 241 0.288889 242 0.961686 243 0.094402 244 0.960526 245 1.000000 246 0.166667 247 0.373494 248 0.000000 249 0.839416 250 0.862745 251 0.589873 252 0.983871 253 0.751938 254 0.000000 255 0.594937 256 0.259615 257 0.459916 258 0.935065 259 0.969231 260 0.755814
而不是简单的直方图:
df.hist()
我需要创建一个条形图,其中每个条形图将计算预定义范围内的多个实例.
例如,下面的图应该有三个条形,其中的点数分为:[0 0.35],[0.35 0.7] [0.7 1.0]
编辑
非常感谢你的回答.另一个问题,如何订购垃圾箱?
例如,我得到以下结果:
In[349]: out.value_counts() Out[349]: [0, 0.001] 104 (0.001, 0.1] 61 (0.1, 0.2] 32 (0.2, 0.3] 20 (0.3, 0.4] 18 (0.7, 0.8] 6 (0.4, 0.5] 6 (0.5, 0.6] 5 (0.6, 0.7] 4 (0.9, 1] 3 (0.8, 0.9] 2 (1, 1.001] 0
如你所见,最后三个箱子没有订购.如何根据“类别”或我的垃圾箱对数据框进行排序?
编辑2
刚刚找到了如何解决它,只需使用’reindex()’:
In[355]: out.value_counts().reindex(out.cat.categories) Out[355]: [0, 0.001] 104 (0.001, 0.1] 61 (0.1, 0.2] 32 (0.2, 0.3] 20 (0.3, 0.4] 18 (0.4, 0.5] 6 (0.5, 0.6] 5 (0.6, 0.7] 4 (0.7, 0.8] 6 (0.8, 0.9] 2 (0.9, 1] 3 (1, 1.001] 0
pd.cut 将值分区为与每个区间对应的区间,然后使用
pd.value_counts
获取每个区间的总计数.稍后绘制条形图,另外将X轴刻度标签替换为特定刻度所属的类别名称.
out = pd.cut(s, bins=[0, 0.35, 0.7, 1], include_lowest=True)
ax = out.value_counts(sort=False).plot.bar(rot=0, color="b", figsize=(6,4))
ax.set_xticklabels([c[1:-1].replace(","," to") for c in out.cat.categories])
plt.show()
如果希望Y轴显示为相对百分比,请将频率计数标准化并将结果乘以100.
out = pd.cut(s, bins=[0, 0.35, 0.7, 1], include_lowest=True)
out_norm = out.value_counts(sort=False, normalize=True).mul(100)
ax = out_norm.plot.bar(rot=0, color="b", figsize=(6,4))
ax.set_xticklabels([c[1:-1].replace(","," to") for c in out.cat.categories])
plt.ylabel("pct")
plt.show()
翻译自:https://stackoverflow.com/questions/43005462/pandas-bar-plot-with-binned-range
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Google總部大揭密
史蒂芬.李維 / 陳重亨 / 財信 / 2011-11
∣如果有一天,Google的搜尋引擎突然故障 ∣GMAIL信件全數消失 ∣Google Maps、Google Docs、Google行事曆等所有雲端服務全面停擺 ∣我們該怎麼辦?! 歷史上像Google如此成功,且廣受推崇的企業可沒幾家。它改變了網路的使用方式,也成了我們生活不可或缺的一部分。這到底是怎麼辦到的? 《連線》雜誌資深主筆史蒂芬.李維史無前例同時取得LS......一起来看看 《Google總部大揭密》 这本书的介绍吧!