首页 > 解决方案 > 如果在其他两列之间,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)

在此处输入图像描述

标签: pythonpandasnumpy

解决方案


就像@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

推荐阅读