python - 测试一个 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"]
解决方案
对于纯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')
如果a
、b
和c
不是 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
推荐阅读
- flutter - 重新加载小部件树时未重新创建颤振 BlocProvider
- python - 为什么我的函数在通过 if 语句时不起作用?
- java - while((message = reader.readLine()) != null) 是无限循环吗?
- javascript - 如何将文本文件读入 JavaScript 中的对象数组
- javascript - Quill 富文本编辑器:如何将文件输入按钮附加到工具栏并嵌入到编辑器
- javascript - 如何设置状态
- linux - Logstash 在 Ubuntu 中没有显示任何输出
- google-apps-script - 谷歌脚本 DriveApp.getFolders().hasNext() 错误
- javascript - 同时更改范围滑块和输入框的值
- javascript - 谷歌翻译、必应翻译等网站如何工作?