使用 Pandas,如果一列 ( x
) 中的值介于其他两列 (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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句