gpt4 book ai didi

python Pandas : categorize/bin by numeric groupings with zero values

转载 作者:行者123 更新时间:2023-11-28 21:03:41 28 4
gpt4 key购买 nike

我不确定这是否是最有效的方式,但我正在努力将客户支出分组到箱子/桶中。

这是我正在处理的 df:

df.head()

Best_ID_S| Dollar
abc2464 0.00
fdhg357 672.00
hjg5235 250.00
mjhur57 199.00
erew3452 116.25

这是我的代码:

bins = [0,250,500,750,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000,8000,1000000000000]
#I didn't know how to create 8000+ so I just added a crazy number in the end, it works

group_names = ['0-250','251-500','501-749','750-999','1000-1499','1500-1999','2000-2499','2500-2999','3000-3499','3500-3999','4000-4499','4500-4999','5000-5499','5500-5999','6000-6499','6500-6999','7000-7499','8000+']

categories = pd.cut(df_2014['Dollar'], bins, labels=group_names)
df['Category'] = pd.cut(df['Dollar'], bins, labels=group_names)
df['Buckets'] = pd.cut(df['Dollar'], bins)

这是我在执行 df.head() 时得到的结果:

Best_ID_S| Dollar | Category |  Buckets
abc2464 0.00 NaN
fdhg357 672.00 501-749 (500, 750]
hjg5235 250.00 0-250 (0, 250]
mjhur57 199.00 0-250 (0, 250]
erew3452 116.25 0-250 (0, 250]

如果 Dollar Value 是 0,我需要它是 0-250 的桶。但我得到了 NaN。

最佳答案

right 参数的默认值为 true。数学上 ( 表示不包括左边的,所以需要 [ 来包含左边的值。所以将 pd.cut 更改为

df['Category'] = pd.cut(df['Dollar'], bins, labels=group_names,right=False)
df['Buckets'] = pd.cut(df['Dollar'], bins,right=False)
 Best_ID_S|  Dollar Category     Buckets0    abc2464    0.00    0-250    [0, 250)1    fdhg357  672.00  501-749  [500, 750)2    hjg5235  250.00  251-500  [250, 500)3    mjhur57  199.00    0-250    [0, 250)4   erew3452  116.25    0-250    [0, 250)

如果要使其包含左侧,您还可以通过保持右侧参数 Trueinclude_lowest 设置为 True

关于 python Pandas : categorize/bin by numeric groupings with zero values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283711/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com