为什么numpy的很多ndarray方法都有对应的函数? [英] Why does numpy have a corresponding function for many ndarray methods?

查看:28
本文介绍了为什么numpy的很多ndarray方法都有对应的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个例子:

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

...还有很多.是为了支持一些遗留代码,还是有更好的理由?而且,我是仅根据代码的外观"进行选择,还是两种方式中的一种比另一种更好?

... and quite a few more. Is it to support some legacy code, or is there a better reason for that? And, do I choose only on the basis of how my code 'looks', or is one of the two ways better than the other?

我可以想象,人们可能希望 numpy.dot() 使用 reduce(例如,reduce(numpy.dot, A, B, C,D)) 但我不认为这对 numpy.sum() 之类的东西有用.

I can imagine that one might want numpy.dot() to use reduce (e.g., reduce(numpy.dot, A, B, C, D)) but I don't think that would be as useful for something like numpy.sum().

推荐答案

正如其他人所指出的,同名的 NumPy 函数和数组方法通常是等效的(它们最终调用相同的底层代码).如果更容易阅读,其中一个可能比另一个更受欢迎.

As others have noted, the identically-named NumPy functions and array methods are often equivalent (they end up calling the same underlying code). One might be preferred over the other if it makes for easier reading.

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

However, in some instances the two behave different slightly differently. In particular, using the ndarray method sometimes emphasises the fact that the method is modifying the array in-place.

例如,np.resize 返回一个具有指定形状的 new 数组.另一方面,ndarray.resize 就地改变数组的形状.每种情况使用的填充值也不同.

For example, np.resize returns a new array with the specified shape. On the other hand, ndarray.resize changes the shape of the array in-place. The fill values used in each case are also different.

类似地,a.sort() 对数组 a 进行就地排序,而 np.sort(a) 返回一个已排序的副本.

Similarly, a.sort() sorts the array a in-place, while np.sort(a) returns a sorted copy.

这篇关于为什么numpy的很多ndarray方法都有对应的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆