python - 创建一个新列,该列取决于熊猫中其他列的值范围
问题描述
我有一个示例熊猫数据框:
datetime column1
2021.04.10 01:00:00. 10
2021.04.11 02:00:00 15
2021.04.11 03:00:00. 5
2021.04.11 04:00:00. 20
2021.04.11 05:00:00. 15
2021.04.11 06:00:00. 2
我想创建一个名为 position 的新列,如果 clolumn1 的值小于 10,则为 25%,当 column1 值 >=10 和 <15 时,值为 40%,当 column1 值为 100% 时,值为>=15。
示例输出如下所示:
datetime column1. position
2021.04.10 01:00:00. 10. 40%
2021.04.11 02:00:00 15. 100%
2021.04.11 03:00:00. 5. 25%
2021.04.11 04:00:00. 20. 100%
2021.04.11 05:00:00. 15. 100%
2021.04.11 06:00:00. 2. 25%
解决方案
pd.cut
这是一种pd.cut
用于将值分类/分类为column1
具有预定义标签的离散间隔的方法。
df['position'] = pd.cut(df['column1'],
bins=[-np.inf, 10, 15, np.inf],
labels=['25%', '40%', '100%'], right=False)
datetime column1 position
0 2021.04.10 01:00:00. 10 40%
1 2021.04.11 02:00:00 15 100%
2 2021.04.11 03:00:00. 5 25%
3 2021.04.11 04:00:00. 20 100%
4 2021.04.11 05:00:00. 15 100%
5 2021.04.11 06:00:00. 2 25%
推荐阅读
- javascript - 如何修复 jQuery 中的重复回调
- c# - 阻止 Visual Studio 测试资源管理器发现共享 .NET Standard 库中的测试
- python - 如何使用循环初始化多个对象,并为每个对象获取不同的用户输入?
- javascript - 卡在 Goomba 的速度并在游戏结束时取消动画
- python - 使用 opencv 在数字和单词周围放置边界框
- macos - Electron 应用程序中带有淡入淡出过渡的全屏
- java - 处理 Java 和 Oracle DB 之间的数百万个请求
- java - 如何在 Java 中为 HashMap 编写 put 方法?
- azure - 作为 Azure 数据工厂的一部分,如何解压缩并执行批处理服务作业
- php - 如何修复 bind_param“无法传递参数”