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

标签 python pandas grouping nan categories

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

这是我正在处理的 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     Buckets
0    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/

相关文章:

python - Azure FUnctions Enum RpcLogCategory 内的 Pinecone 没有为名称 'User' 定义值

python - 如何将正则表达式与 pandas series.find 函数一起使用

python - 如何只保留 pandas DataFrame 中具有多个值的行?

Pandas - 分为 24 小时区 block ,但不是午夜到午夜

Python - 对存储在字典中的列表中的项目进行计数和分组

python - 在 Google Cloud SDK 内的 python 脚本中执行 Node 脚本

python - pyenchant 在 Mac OS X 上找不到字典文件

python - 类中的条件语句,但在函数范围之外

python - 二值图像数据帧到欧几里德坐标

用于根据不均匀日期创建不均匀组的 R 函数