为什么numpy对很多ndarray方法都有对应的函数呢?

Why does numpy have a corresponding function for many ndarray methods?

举几个例子:

numpy.sum()
ndarray.sum()
numpy.amax()
ndarray.max()
numpy.dot()
ndarray.dot()

...还有很多。是为了支持一些遗留代码,还是有更好的理由?而且,我是仅根据我的代码如何选择 'looks',还是两种方法中的一种比另一种更好?

我可以想象有人可能希望 numpy.dot() 使用 reduce(例如 reduce(numpy.dot, A, B, C, D)),但我认为这对 [=14 这样的东西没有用处=].

正如其他人所指出的,同名的 NumPy 函数和数组方法通常是等价的(它们最终调用相同的底层代码)。如果阅读起来更容易,可能会更喜欢一个。

但是,在某些情况下,两者的行为略有不同。特别是,使用 ndarray 方法有时会强调该方法是就地修改数组这一事实。

例如,np.resize returns a new array with the specified shape. On the other hand, ndarray.resize 就地更改数组的形状。每种情况下使用的填充值也不一样

类似地,a.sort() 就地对数组 a 进行排序,而 np.sort(a) returns 排序后的副本。

大多数情况下,该方法是基本编译版本。该函数在可用时使用该方法,但在参数不是数组时也有某种备份。查看函数或方法的代码 and/or 文档会有所帮助。

例如,如果在 Ipython 我要求查看 sum 方法的代码,我看到它是编译代码

In [711]: x.sum??
Type:        builtin_function_or_method
String form: <built-in method sum of numpy.ndarray object at 0xac1bce0>
...
Refer to `numpy.sum` for full documentation.

np.sum 上做同样的事情我得到了很多行文档和一些 Python 代码:

   if isinstance(a, _gentype):
        res = _sum_(a)
        if out is not None:
            out[...] = res
            return out
        return res
    elif type(a) is not mu.ndarray:
        try:
            sum = a.sum
        except AttributeError:
            return _methods._sum(a, axis=axis, dtype=dtype,
                                out=out, keepdims=keepdims)
        # NOTE: Dropping the keepdims parameters here...
        return sum(axis=axis, dtype=dtype, out=out)
    else:
        return _methods._sum(a, axis=axis, dtype=dtype,
                            out=out, keepdims=keepdims)

如果我调用 np.sum(x) 其中 x 是一个数组,它最终会调用 x.sum():

    sum = a.sum
    return sum(axis=axis, dtype=dtype, out=out)

np.amax 相似(但更简单)。请注意 np. 形式可以处理不是数组的对象(没有方法),例如列表:np.amax([1,2,3]).

np.dotx.dot都显示为'built-in'函数,所以我们不能说什么优先级。他们可能最终都调用了一些底层 C 函数。

np.reshape 是另一个如果可能的话委托:

try:
    reshape = a.reshape
except AttributeError:
    return _wrapit(a, 'reshape', newshape, order=order)
return reshape(newshape, order=order)

因此 np.reshape(x,(2,3)) 在功能上与 x.reshape((2,3)) 相同。但是 _wrapit 表达式启用 np.reshape([1,2,3,4],(2,2)).

np.sort returns 通过对副本进行就地排序的副本:

a = asanyarray(a).copy()
a.sort(axis, kind, order)
return a

x.resize 是内置的,而 np.resize 最终会执行 np.concatenatereshape.

如果您的数组是一个子类,如矩阵或掩码,它可能有自己的变体。矩阵.sum的作用是:

return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)

详细说明 Peter 的评论以提高可见度:

We could make it more consistent by removing methods from ndarray and sticking to just functions. But this is impossible because it would break everyone's existing code that uses methods.

Or, we could move all functions to also be methods. But this is impossible because new users and packages are constantly defining new functions. Plus continuing to multiply these duplicate methods violates "there should be one obvious way to do it".

If we could go back in time then I'd probably argue for not having these methods on ndarray at all, and using functions exclusively. ... So this all argues for using functions exclusively

numpy issue: More consistency with array-methods #7452