找不到np.argsort()实现



我想看看numpy.argsort()是如何工作的。

  1. 在文档中,numpy.argsort()的源是numpy.core.fromnumeric.py。这是可以理解的。https://numpy.org/doc/stable/reference/generated/numpy.argsort.html

  2. core.fromnumeric.argsort()稍微复杂一些
    忽略decorator,如果fromnumeric.argsort(arr)返回_wrapfunc(arr, "argsort"),则返回arr.argsort()。这不是问题
    假设arrnumpy.ndarray,它可能在array_api.__init__.py中。https://github.com/numpy/numpy/blob/v1.21.0/numpy/core/fromnumeric.py

  3. CCD_ 11来自CCD_。好啊https://github.com/numpy/numpy/blob/main/numpy/array_api/__init__.py

  4. CCD_ 13调用CCD_。这就是我最初想要的。它是圆形的。https://github.com/numpy/numpy/blob/main/numpy/array_api/_sorting_functions.py

额外

  1. numpy.__init__.pyi中,numpy.argsort()来自core.fromnumerichttps://github.com/numpy/numpy/blob/main/numpy/__init__.pyi

    CCD_ 18和CCD_。

这些是循环引用吗?我当然知道这些工作。2.中的it might be in array_api.__init__.py.是否错误?那么,它的实际实施地点在哪里呢?


此问题的背景

我注意到CCD_ 22在CCD_。我想在已排序的数组上运行np.unique,但发现np.unique调用np.argsort。因此,我试图找出np.argsortnp.sort之间的差异,并需要更多地了解np.argsort

为什么要查看源代码?要在自己的c代码项目中实现它吗?我认为这不会帮助你在python中更有效地使用它。在Ipython会话中,我使用??

In [22]: np.argsort??
...
return _wrapfunc(a, 'argsort', axis=axis, kind=kind, order=order)

好吧,这是一个函数将责任推卸给方法的典型情况。如果需要,函数版本会将输入转换为数组,然后调用数组的方法。通常,功能版本有更完整的文档,但功能基本相同。

In [21]: arr.argsort??
Type:      builtin_function_or_method

通常故事到此结束。

另一种方法是单击文档上的[source]链接。这也引出了同样的事情。

注意:

@array_function_dispatch(_argsort_dispatcher)

最近的版本增加了这个CCD_ 33层;查看发行说明了解更多详细信息。根据我的经验,这只会让搜索代码变得更加困难。

另一个步骤是转到github并进行搜索。有时这会带来一些有用的东西,但往往是徒劳的。

作为一个用户,我不需要知道;如何";详细信息。阅读文档很容易,如果我还有问题的话,可以做一些实验。深入研究c代码并不能更好地使用它。

至于你补充的问题:

所有CCD_ 36对象都是";"多阵列";,具有从0到32个维度的任意维度。

github

numpygithub上,我搜索了argsort,并选择了最有前途的文件,numpy/core/src/multirarray/methods.c

这具有功能

array_argsort(PyArrayObject *self,
PyObject *const *args, Py_ssize_t len_args, PyObject *kwnames)

跳过似乎处理输入参数的代码,看起来工作已经在中完成

res = PyArray_ArgSort(self, axis, sortkind);

这似乎是在numpy/core/src/multirarray/item_selection.c 中定义的

PyArray_ArgSort(PyArrayObject *op, int axis, NPY_SORTKIND which)
...
if (argsort == NULL) {
if (PyArray_DESCR(op)->f->compare) {
switch (which) {
default:
case NPY_QUICKSORT:
argsort = npy_aquicksort;
break;
case NPY_HEAPSORT:
argsort = npy_aheapsort;
break;
case NPY_STABLESORT:
argsort = npy_atimsort;
break;
...
ret = _new_argsortlike(op2, axis, argsort, NULL, NULL, 0);

等等。。。。

所有这些都无助于我更好地使用它。

最新更新