NumPy: Difference between revisions

From David's Wiki
(Created page with "NumPy is a python library for working with arrays. ==Memory Usage== To optimize memory usage, try to use views instead of actual arrays where possible. Indexing into an arr...")
 
No edit summary
Line 14: Line 14:
To output to an existing array <code>c</code>, you can use <code>np.add(a, b, out=c)</code>.   
To output to an existing array <code>c</code>, you can use <code>np.add(a, b, out=c)</code>.   
If you need to perform an operation over multiple arrays, you can use [https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html np.ufunc.reduce]. E.g. <code>np.logical_and.reduce((a, b, c))</code>.
If you need to perform an operation over multiple arrays, you can use [https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html np.ufunc.reduce]. E.g. <code>np.logical_and.reduce((a, b, c))</code>.
===Batched Multiplication===
If you need batched matrix multiplication, use [https://numpy.org/doc/stable/reference/generated/numpy.tensordot.html <code>np.tensordot</code>].

Revision as of 14:54, 6 February 2021

NumPy is a python library for working with arrays.

Memory Usage

To optimize memory usage, try to use views instead of actual arrays where possible.
Indexing into an array will return a view. See numpy indexing for details.
Fancy indexing, using a list of indices, will not return a view.

The following functions also return views

Most function calls will return a new array. E.g. a+b will return a new array with the broadcasted size which requires memory allocation.
To output to an existing array c, you can use np.add(a, b, out=c).
If you need to perform an operation over multiple arrays, you can use np.ufunc.reduce. E.g. np.logical_and.reduce((a, b, c)).

Batched Multiplication

If you need batched matrix multiplication, use np.tensordot.