Python:使用Pandas进行装箱和可视化

Python:使用Pandas进行装箱和可视化,python,pandas,cut,binning,Python,Pandas,Cut,Binning,我对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]箱子显示为[17.99-22] 我想要的:我想要它显示18-22 以下是绘图代码: plt.figure(figsize=(15,8)) dist = sns.

我对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]箱子显示为[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'),(categories=[(17.999,22.0],(22.0,27.0],(27.0,32.0],(32.0,37.0],(37.0,42.0],(42.0,47.0],(47.0,52.0],(52.0,57.0],(57.0,60.0]),ordered=True)即使我将其更改为int64,数据类型仍然是一个float.int:定义x范围内的等宽箱子的数量。x的范围每边扩展0.1%,以包括x的最小值和最大值。这是在文档上