首页 > 解决方案 > 测试一个 numpy 数组是否在数组 a 和 b 之间

问题描述

说我有三个 numpy 数组:

a = np.array([8,2,10,10])
b = np.array([5,6,7,8])
c = np.array([9,10,11,12])

如果a在b和c之间,我想做一个元素测试。如果是这样,返回类似:

["Pass","Fail","Pass","Pass"]

标签: pythonpandasnumpy

解决方案


对于纯numpy解决方案,您可以使用np.where()

np.where((b < a) & (a < c), 'Pass', 'Fail')

# array(['Pass', 'Fail', 'Pass', 'Pass'], dtype='<U5')

如评论中所述,如果您需要b<a<c或,则需要进行额外检查c<a<b

bac = (b < a) & (a < c)
cab = (c < a) & (a < b)
np.where(bac | cab, 'Pass', 'Fail')

如果abc不是 numpy 数组本身,而是列表的列:

a = np.array([[8,2,3], 2, 10, 10], dtype=object)
b = np.array([[5,4,5], 6, 7, 8], dtype=object)
c = np.array([[9,6,7], 10, 11, 12], dtype=object)
df = pd.DataFrame({'a': a, 'b': b, 'c': c})

#            a          b          c
# 0  [8, 2, 3]  [5, 4, 5]  [9, 6, 7]
# 1          2          6         10
# 2         10          7         11
# 3         10          8         12

用于applymap()将每个单元格转换为 numpy 数组,然后apply()进行中间性测试axis=1

def between(row):
    bac = (row.b < row.a) & (row.a < row.c)
    cab = (row.c < row.a) & (row.a < row.b)
    return np.where(bac | cab, 'Pass', 'Fail')

df = df.applymap(np.array)
df.apply(between, axis=1)

# 0    [Pass, Fail, Fail]
# 1                  Fail
# 2                  Pass
# 3                  Pass
# dtype: object

推荐阅读