SciPy Recipes
上QQ阅读APP看书,第一时间看更新

Operations on arrays

NumPy defines a rich set of operations and functions for the ndarray type. NumPy defines the notion of a universal function, abbreviated as ufunc, which is a function object that can be applied to arbitrary arrays. Universal functions are objects of ufunc type, and NumPy provides a vast collection of built-in ufunc functions, covering all computations needed in scientific and data applications.

A ufunc is specialized towards the element by element application of a function. That is, if x is an array object, and f is a ufunc, the f(x) expression will apply the function f to every element of array x, and return a new object with the resulting values.

A ufunc follows a strict functional protocol; applying the f function to x will never change the elements of the x arrays themselves, but return a new array with the values of f applied to each element of x. User-defined ufunc functions should also follow this protocol.

ufunc functions have many built-in characteristics, the two most important being:

  • Broadcasting, which takes place when a function is applied to arrays that have different shapes. The most common scenario in which this happens is when an array has a single element along one of one axis. Broadcasting will then repeat that same element in an attempt to match the dimensions of other arrays appearing in the function call.
  • Casting, which handles situations in which a function is being applied to arrays of different types.

The rules for broadcasting and casting can be complicated, but most of the time they behave as expected.

ufunc functions are vectorized, that is, they operate on whole array dimensions, instead of on each element separately. In the background, the ufunc function calls C code, so that a loop along an array dimension is much faster than the corresponding Python code. It is recommended that computations in NumPy are done using ufunc functions whenever possible.