簡體   English   中英

將 DataFrame 中的列分箱為 10 個百分位數

[英]Binning a column in a DataFrame into 10 percentiles

我正在尋找 qcut 或將我的“金額”列切割成 10 個百分位數的箱子。 基本上是 describe() 功能,但有 0-10%、11-20%、21-30%、31-40%、41-50%、51-60%、61-70%、71-80%、81- 90%, 91-100% 代替。

在分箱之后,我想創建一個顯示 1-10 的列,指示特定數量所在的分箱。

我已經嘗試使用下面的代碼,但是,我不相信它可以達到我想要的效果。

groups = df.groupby(pd.cut(df['Amount'], 10)).size()

這是我的數據框!

df.shape
Out[5]: (1385, 2)

df.head(10)
Out[6]: 
   Amount         New or Repeat Customer
0  23044                    New
1  15509                    New
2   6184                    New
3   6184                    New
4   5828                    New
5   5461                    New
6   5143                    New
7   5027                    New
8   4992                    New
9   4698                 Repeat

使用pd.qcut

# Sample data
size = 100
df = pd.DataFrame({
    'Amount': np.random.randint(5000, 20000, size),
    'CustomerType': np.random.choice(['New', 'Repeat'], size)
})

# Binning
labels = ['0% to 10%'] + [f'{i+1}% to {i+10}%' for i in range(10, 100, 10)]
df['Bin'] = pd.qcut(df['Amount'], 10, labels=labels)

結果:

   Amount CustomerType          Bin
0   15597       Repeat   61% to 70%
1   14498          New   51% to 60%
2    6373       Repeat    0% to 10%
3    9901       Repeat   21% to 30%
4   18450       Repeat  91% to 100%
5    9337       Repeat   21% to 30%
6   19310       Repeat  91% to 100%
7   11198          New   31% to 40%
8   12485          New   41% to 50%
9   11130          New   31% to 40%

暫無
暫無

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

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