使用 Pandas 进行分箱和可视化

问题描述 投票:0回答:2

所以我正在尝试为我的数据框创建一个年龄间隔列:

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 seaborn cut binning
2个回答
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')


1
投票

条形图在这里具有误导性,因为箱子的宽度不相等。年龄是连续变量。为什么要掩盖垃圾箱彼此相邻的事实?

这正是直方图有用的设置。您仍然可以自定义垃圾箱并相应地设置刻度线。其他情节定制也同样有效。

import numpy as np
import pandas as pd
import seaborn as sns
sns.set()

df = pd.DataFrame({'Age': np.random.normal(35, 10, 1000)})
bins = [18, 22, 27, 32, 37, 42, 47, 52, 57, 60]

ax = sns.histplot(data=df, x='Age', bins=bins)
ax.set_xticks(bins)

© www.soinside.com 2019 - 2024. All rights reserved.