我应该使用 np.Absol还是 np.abs?

Numpy 提供了 np.absolute和通过

from .numeric import absolute as abs

这明显违反了 蟒蛇之禅法案:

应该有一种——最好只有一种——显而易见的方法来做到这一点。

所以我猜这是有原因的。

我个人在几乎所有的代码中都使用了 np.abs,比如在 Stack Overflow 上查看 Np.abs绝对的的搜索结果的数量,似乎绝大多数都是一样的(2130对244次点击)。

有什么理由我应该优先使用 np.absolute而不是 np.abs在我的代码,或者我应该只是去更“标准”的 np.abs

145761 次浏览

It's likely because there a built-in functions with the same name, abs. The same is true for np.amax, np.amin and np.round_.

The aliases for the NumPy functions ABC0, ABC1, ABC2 and round are only defined in the top-level package.

So np.abs and np.absolute are completely identical. It doesn't matter which one you use.

There are several advantages to the short names: They are shorter and they are known to Python programmers because the names are identical to the built-in Python functions. So end-users have it easier (less to type, less to remember).

But there are reasons to have different names too: NumPy (or more generally 3rd party packages) sometimes need the Python functions abs, min, etc. So inside the package they define functions with a different name so you can still access the Python functions - and just in the top-level of the package you expose the "shortcuts". Note: Different names are not the only available option in that case: One could work around that with the Python module builtins to access the built-in functions if one shadowed a built-in name.

It might also be the case (but that's pure speculation on my part) that they originally only included the long-named functions absolute (and so on) and only added the short aliases later. Being a large and well-used library the NumPy developers don't remove or deprecate stuff lightly. So they may just keep the long names around because it could break old code/scripts if they would remove them.

There also is Python's built-in abs(), but really all those functions are doing the same thing. They're even exactly equally fast! (This is not the case for other functions, like max().)

enter image description here

Code to reproduce the plot:

import numpy as np
import perfplot




def np_absolute(x):
return np.absolute(x)




def np_abs(x):
return np.abs(x)




def builtin_abs(x):
return abs(x)




b = perfplot.bench(
setup=np.random.rand,
kernels=[np_abs, np_absolute, builtin_abs],
n_range=[2 ** k for k in range(25)],
xlabel="len(data)",
)
b.save("out.png")
b.show()