numpy 数学和统计方法的语法

numpy 数学和统计方法的语法是怎样的?
以下代码运行结果是一样的,那么存在底层什么差异?


arr = np.random.randn(2, 4)
print("平均数:", arr.mean())
print("平均数:", np.mean(arr))


为什么numpy的array那么快? - 知乎 在python numpy中,如果我用10^6长度随机生成的list生成numpy array,那么生成耗时0.1s, 但是得到这个arra… https://www.zhihu.com/question/30823702

两种写法都行的,没什么差异

这是同一个函数在不同命名空间是否都有映射的问题。ndarray的大部分方法在顶层命名空间有映射,因此可以有两种写法。比如题主提到的mean,还有求和、极值等。

>> a = np.random.random((2,3))
>>> a.max(), np.max(a), np.nanmax(a)
(0.8424801237335697, 0.8424801237335697, 0.8424801237335697)
>>> a.sum(), np.sum(a), np.nansum(a)
(3.258676571350724, 3.258676571350724, 3.258676571350724)

不过,也有例外。比如,同样是复制功能,深复制copy两种写法都可以,但浅复制view则只能数组的方法可用,顶层命名空间没有映射。

>>> a.copy()
array([[0.7584572 , 0.63767601, 0.84248012],
       [0.49021339, 0.17332206, 0.35652779]])
>>> np.copy(a)
array([[0.7584572 , 0.63767601, 0.84248012],
       [0.49021339, 0.17332206, 0.35652779]])
>>> a.view()
array([[0.7584572 , 0.63767601, 0.84248012],
       [0.49021339, 0.17332206, 0.35652779]])
>>> np.view(a)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    np.view(a)
  File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\site-packages\numpy\__init__.py", line 304, in __getattr__
    "{!r}".format(__name__, attr))
AttributeError: module 'numpy' has no attribute 'view'

另外,在顶层空间命名的一些函数,是不能作为数组方法使用的。比如,where、stack、sin、rollaxis等函数。

>>> np.where(a>0.5)
(array([0, 0, 0], dtype=int64), array([0, 1, 2], dtype=int64))