python - 如果在其他两列之间,Pandas 有效地添加新列 true/false
问题描述
x
使用 Pandas,如果一列 ( ) 中的值介于其他两列 (low
和) 中的值之间,我如何有效地添加一个新列是真/假high
?
np.select
从这里开始的方法非常有效,但我“感觉”应该有一种单一的方式来做到这一点。
使用 Python 3.7
fid = [0, 1, 2, 3, 4]
x = [0.18, 0.07, 0.11, 0.3, 0.33]
low = [0.1, 0.1, 0.1, 0.1, 0.1]
high = [0.2, 0.2, 0.2, 0.2, 0.2]
test = pd.DataFrame(data=zip(fid, x, low, high), columns=["fid", "x", "low", "high"])
conditions = [(test["x"] >= test["low"]) & (test["x"] <= test["high"])]
labels = ["True"]
test["between"] = np.select(conditions, labels, default="False")
display(test)
解决方案
就像@Brebdan 提到的,你可以使用这个内置:
test["between"] = test["x"].between(test["low"], test["high"])
输出:
fid x low high between
0 0 0.18 0.1 0.2 True
1 1 0.07 0.1 0.2 False
2 2 0.11 0.1 0.2 True
3 3 0.30 0.1 0.2 False
4 4 0.33 0.1 0.2 False
推荐阅读
- r - 导出到 PDF 时,如何获得 geom_point 绘图的 stroke = 0?
- c# - CreateCompatibleDC(IntPtr.Zero) 返回 IntPtr.Zero
- javascript - location.reload(true) 在谷歌浏览器中不起作用
- python - 如何循环浏览打开的文本文件并在发送电子邮件时保持打开状态?
- javascript - 从节点到 mySQL 数据库进行动态查询
- python - 使用 np.select 根据来自多个其他列的数据生成条件列
- c# - 实体框架模型不包含架构信息
- java - MongoDb spring数据查询二进制和UUID
- swift - 从 String 到 NSString 的条件转换总是成功
- javascript - 在 pre 标签内查找特殊字符并包裹在 div 标签中