【问题标题】:Python: Binning and Visualization with PandasPython:使用 Pandas 进行分箱和可视化
【发布时间】:2020-10-21 05:36:29
【问题描述】:

我对 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()

谢谢

【问题讨论】:

    标签: python pandas cut binning


    【解决方案1】:

    那是因为它是一个 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')

    【讨论】:

    • CategoricalDtype(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,但dtype还是一个float。
    • int :定义 x 范围内等宽 bin 的数量。 x 的范围每边都扩展了 0.1%,以包括 x 的最小值和最大值。这是在 pandas 文档中
    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 2013-06-27
    • 2019-10-13
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多