python - np.searchsorted() 背后有一个有趣的算法吗?

标签 python numpy vectorization

searchsorted() 函数对于在 numpy 中组织数据非常有用,并且它特别适合大型数组。

为什么这么快?是不是就是这样(类似于矢量化代码),我们可以让代码直接在“C”中运行。但是我是否可以在 numpy 中通过更基本的函数获得类似的东西?我可以编写(使用matlab的人所说的)“向量化代码”来执行searchsorted的操作吗?

最佳答案

Spyder(IPython 控制台)和线条魔法很有用...

np.searchsorted??
Signature: np.searchsorted(a, v, side='left', sorter=None)
Source:   
@array_function_dispatch(_searchsorted_dispatcher)
def searchsorted(a, v, side='left', sorter=None):
    """
    Find indices where elements should be inserted to maintain order.
... huge snip
    This function uses the same algorithm as the builtin python `bisect.bisect_left`
    (``side='left'``) and `bisect.bisect_right` (``side='right'``) functions,
    which is also vectorized in the `v` argument.
... ditto    
    """
    return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
File:      c:\...source path...\lib\site-packages\numpy\core\fromnumeric.py
Type:      function

因此,如果需要实际的算法详细信息,搜索将在 python 端进行二等分。

关于python - np.searchsorted() 背后有一个有趣的算法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58721909/

相关文章:

python - 如何从 linux 命令行获取输入到我的 Python 脚本中?

python - 禁用控制台窗口的关闭按钮

python - 重复出现一列的值并更新另一列的值

python - Python numpy 中的无循环卡方网格搜索

python - Python 中的快速求和

python - 向量化 Numpy 切片操作

python - 使用 setup.py bdist_wininst 构建的 Windows 安装程序在安装时触发 RuntimeError。我该如何解决?

python - PyCharm 无法识别已安装的模块

python - PyTorch张量高级索引

python - 索引到 numpy mgrid