Search code examples
pythonarraysnumpymultidimensional-arraymask

Numpy: copyto returns None


When I use np.copyto, it always returns None:

import numpy as np
a = np.random.random((3,3))
b = np.zeros_like(a)
b[:,0] = 100
b_nonzero_mask = b.astype(bool)
c = np.copyto(a, b, where=b_nonzero_mask)
print(c)  # None

How is the function supposed to be used?


Solution

  • In Python, by default, if a function does not have a return statement it returns None. The np.copyto definition does not return anything. Instead, it rewrites a in place.

    So, you have to copy a beforehand:

    import numpy as np
    a = np.random.random((3,3))
    b = np.zeros_like(a)
    b[:,0] = 100
    b_nonzero_mask = b.astype(bool)
    c = np.copy(a)
    np.copyto(c, b, where=b_nonzero_mask)