python - pandas中连续变量的动态分箱
问题描述
我在熊猫中有以下数据框
Index Quantity
1 12
2 23
3 24.45
4 0.56
5 100.23
6 50.45
我想要的数据框是
Index Quantity bins
1 12 10-14.99
2 23 20-24.99
3 24.45 20-24.99
4 0.56 0-4.99
5 100.23 100-104.99
6 50.45 50-54.99
我怎样才能在熊猫中做到这一点?
解决方案
这是你需要的吗?
s1=((df.Quantity//5)*5).min()
s2=((df.Quantity//5+1)*5).max()
s1
Out[527]: 0.0
s2
Out[528]: 105.0
pd.cut(df.Quantity,np.arange(s1,s2+5,5))
Out[529]:
0 (10.0, 15.0]
1 (20.0, 25.0]
2 (20.0, 25.0]
3 (0.0, 5.0]
4 (100.0, 105.0]
5 (50.0, 55.0]
Name: Quantity, dtype: category
推荐阅读
- mysql - MySQL - 查询获取速度非常慢
- wiremock - WireMock 提供来自文件的响应并保持连接处于活动状态
- python - CSV 为每个条目留下一个空白行
- visual-studio - 安装 expo cli windows 时出错
- open-policy-agent - 如何使用 Open Policy Agent Gatekeeper K8sPSPCapabilities 约束模板将容器列入白名单
- java - 如何构建一个新列表,其中包含现有列表中的所有条目以及修改了一个字段的每个条目的副本?
- jquery - 使用 Gsap 中的 Draw SVG 将 svg 动画从 0% 到 100%
- swift - SwiftUI:扩展数组以获取数组实例的绑定
- react-native - 文本左对齐未以 android 为中心
- django - 如何更改用户的电子邮件并使用 usercreationform 确认它 - django