在分箱列上分组不能正常工作

我正在使用 pandas cut 来计算一个新的 bins 列,如下所示:


bins = [1, 10, 20, 34, np.Inf]

labels = ['1-10', '11-20', '21-34', '35 -Inf']

df['binned'] = pd.cut(df['Number of Locations'], bins=bins, labels=labels, include_lowest=True)

这为我提供了合并值的新列,


然后我尝试下面的代码:


df.groupby(['binned', 'Parent_Account'])['has_desired_product'].apply(sum).reset_index()

这应该给我按新的 binned 列分组,但它给了我不正确的输出 - 实际上只有一个 Parent_Account 用于'35-inf' bin 但它显示的不止于此,我的代码某处有错误吗?


湖上湖
浏览 104回答 1
1回答

互换的青春

没有提供样本数据。测试边缘情况似乎都很好。我正在使用熊猫 1.1df = pd.DataFrame({"Number of Locations":[32,33,34,35,36,np.inf,np.nan,34.0001]})bins = [1, 10, 20, 34, np.Inf]labels = ['1-10', '11-20', '21-34', '35 -Inf']df['binned'] = pd.cut(df['Number of Locations'], bins=bins, labels=labels, include_lowest=True)print(df.to_string())输出   Number of Locations   binned0              32.0000    21-341              33.0000    21-342              34.0000    21-343              35.0000  35 -Inf4              36.0000  35 -Inf5                  inf  35 -Inf6                  NaN      NaN7              34.0001  35 -Inf
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python