[Numpy-discussion] the difference between "+" and np.add?
njs at pobox.com
Thu Nov 22 07:51:23 EST 2012
On Thu, Nov 22, 2012 at 12:41 PM, Chao YUE <chaoyuejoy at gmail.com> wrote:
> Dear all,
> if I have two ndarray arr1 and arr2 (with the same shape), is there some
> difference when I do:
> arr = arr1 + arr2
> arr = np.add(arr1, arr2),
> and then if I have more than 2 arrays: arr1, arr2, arr3, arr4, arr5, then I
> cannot use np.add anymore as it only recieves 2 arguments.
> then what's the best practice to add these arrays? should I do
> arr = arr1 + arr2 + arr3 + arr4 + arr5
> or I do
> arr = np.sum(np.array([arr1, arr2, arr3, arr4, arr5]), axis=0)?
> because I just noticed recently that there are functions like np.add,
> np.divide, np.substract... before I am using all like directly arr1/arr2,
> rather than np.divide(arr1,arr2).
For numpy arrays, a + b just calls np.add(a, b) internally. You can
use whichever looks nicer to you. Usually people just use +
np.add can be more flexible, though. For instance, you can write
np.add(a, b, out=c)
but there's no way to pass extra arguments to the "+" operator.
In fact np.add is not just a function, it's a "ufunc object" (see the
numpy documentation for some more details). So it also provides
np.add.reduce(a) # the same as np.sum (except, sadly, with different defaults)
np.add.accumulate(a) # like np.cumsum
np.add.reduceat(a, indices) # complicated, see docs
And there are lots of these ufunc objects, all of which provide these
same interfaces. Some of them have associated operators like "+", but
More information about the NumPy-Discussion