如何在已排序的 numpy 数组中查找大于给定标量的第一个元素
另请查看如何在已排序的 numpy 数组中查找小于给定标量的第一个元素
你可以像这样使用 np.searchsorted():
find_first_larger.py
idx = np.searchsorted(arr, scalar, side='right') + 1完整示例:
find_first_larger_example.py
import numpy as np
# 示例数组
arr = np.array([1, 2, 3, 4, 5])
# 我们将搜索此值
scalar = 3.5
# 使用 numpy.searchsorted() 查找数组中大于标量的第一个元素
# 我们需要使用 + 1,因为 searchsorted() 返回小于标量的第一个元素
idx = np.searchsorted(arr, scalar, side='right') + 1
# 打印结果索引
print(idx)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow