为什么numpy对许多ndarray方法都有相应的功能? [英] Why does numpy have a corresponding function for many ndarray methods?

查看:71
本文介绍了为什么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天全站免登陆