Ndarray-listener’s documentation¶
- Date
May 17, 2021
- Version
2.0.1
Usage¶
- class ndarray_listener.ndl(input_array)[source]¶
Examples
A scalar is stored as a zero-dimensional array much like a NumPy scalar:
>>> from __future__ import print_function >>> from ndarray_listener import ndl >>> from numpy import atleast_1d >>> >>> class Watcher(object): ... def __init__(self, msg): ... self._msg = msg ... ... def __call__(self): ... print(self._msg + " called me") ... >>> scalar = ndl(-0.5) >>> >>> you0 = Watcher("First guy") >>> you1 = Watcher("Second guy") >>> >>> scalar.talk_to(you0) >>> scalar.itemset(-1.0) First guy called me >>> s0 = scalar.copy() >>> s0.itemset(-0.5) First guy called me >>> s0.talk_to(you1) >>> scalar.itemset(0.0) First guy called me Second guy called me >>> >>> s1 = atleast_1d(scalar) >>> s1[0] = 1.0 First guy called me Second guy called me
One-dimension arrays are also supported:
>>> from ndarray_listener import ndl >>> from numpy import atleast_1d >>> from numpy import set_printoptions >>> >>> set_printoptions(precision=2, suppress=True) >>> >>> vector = ndl([-0.5, 0.1]) >>> >>> you0 = Watcher("First guy") >>> you1 = Watcher("Second guy") >>> >>> vector.talk_to(you0) >>> >>> vector[0] = 0.0 First guy called me >>> vector[:] = 1.0 First guy called me >>> >>> v0 = vector.copy() >>> v0.itemset(0, 1.1) First guy called me >>> >>> v0.itemset(1, 2.2) First guy called me >>> >>> v1 = v0.ravel() >>> >>> v1.talk_to(you1) >>> vector[-1] = 9.9 First guy called me Second guy called me
- itemset(*args)[source]¶
Insert scalar into an array (scalar is cast to array’s dtype, if possible)
There must be at least 1 argument, and define the last argument as item. Then,
a.itemset(*args)
is equivalent to but faster thana[args] = item
. The item should be a scalar value and args must select a single item in the array a.- Parameters
*args (Arguments) – If one argument: a scalar, only used in case a is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple.
Notes
Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular location in an ndarray, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.
Examples
>>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[2, 2, 6], [1, 0, 6], [1, 0, 9]])
Comments and bugs¶
You can get the source and open issues on Github.