簡體   English   中英

Python:使用 Pandas 進行分箱和可視化

[英]Python: Binning and Visualization with 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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM