python - Python:使用 Pandas 进行分箱和可视化
问题描述
我对python很陌生。
所以我正在尝试为我的数据框制作一个年龄间隔列
df['age_interval'] = pd.cut(x=df['Age'], bins=[18, 22, 27, 32, 37, 42, 47, 52, 57, 60], include_lowest=True)
我添加了我的图表:
问题:在可视化中,[18-22] bin 显示为 [17.99-22]
我想要什么:我希望它显示 18-22。
下面是情节代码:
plt.figure(figsize=(15,8))
dist = sns.barplot(x=ibm_ages.index, y=ibm_ages.values, color='blue')
dist.set_title('IBM Age Distribution', fontsize = 24)
dist.set_xlabel('Age Range', fontsize=18)
dist.set_ylabel('Total Count', fontsize=18)
sizes=[]
for p in dist.patches:
height = p.get_height()
sizes.append(height)
dist.text(p.get_x()+p.get_width()/2.,
height + 5,
'{:1.2f}%'.format(height/total*100),
ha="center", fontsize= 8)
plt.tight_layout(h_pad=3)
plt.show()
谢谢
解决方案
那是因为它是一个 float64 类型,你想要一个整数试试:
import numpy as np
df['age_interval'] = pd.cut(x=df['Age'].astype('Int64'), bins=[18, 22, 27, 32, 37, 42, 47, 52, 57, 60], include_lowest=True)
每当您想将 float64 转换为 Int64 时,都可以使用 .astype('Int64')
推荐阅读
- angularjs - ng-bind-html 在 angularjs 代码中的 ng-repeat 中不起作用
- python-3.x - 无法在 python 中使用 BeautifulSoup 从网站上抓取数据
- node.js - 在 ejs 模板中包含一个 .js 文件来操作 DOM 不起作用
- php - 如何在 microsoft sql server management studio 2012 上从 SQL LOGIN 中选择字段
- node.js - 如何使用 Node js 加密 MongoDB 数据库
- python-3.x - 训练自定义 YOLO 模型时损失到 NAN
- javascript - 当手风琴点击时,可打开的手风琴并排展开,我如何只打开点击的手风琴?
- php - 将键添加到索引数组 PHP
- listview - React Native 使用 flatlist 传递 rowId
- python - 对象定位 Keras | 预测整个图像