numpy only perform function on nonzero parts while preserving structure of array

numpy, python

Solution

In [138]: foo = np.array([[ 3.5,  0. ,  2.5,  2. ,  0. ,  1. ,  0. ],
                          [ 0. ,  3. ,  2.5,  2. ,  0. ,  0. ,  0.5],
                          [ 3.5,  0. ,  0. ,  0. ,  1.5,  0. ,  0.5]])
In [141]: mask = foo != 0

In [142]: foo[mask] = foo[mask]+5

In [143]: foo
Out[143]: 
array([[ 8.5,  0. ,  7.5,  7. ,  0. ,  6. ,  0. ],
       [ 0. ,  8. ,  7.5,  7. ,  0. ,  0. ,  5.5],
       [ 8.5,  0. ,  0. ,  0. ,  6.5,  0. ,  5.5]])

Problem

In numpy: ``` Foo = array([[ 3.5, 0. , 2.5, 2. , 0. , 1. , 0. ], [ 0. , 3. , 2.5, 2. , 0. , 0. , 0.5], [ 3.5, 0. , 0. , 0. , 1.5, 0. , 0.5]]) ``` I want to perform a function on Foo such that only the nonzero elements are changed, i.e. for f(x) = x(nonzero)+5: ``` array([[ 8.5, 0. , 7.5, 7. , 0. , 6. , 0. ], [ 0. , 8. , 8.5, 7. , 0. , 0. , 5.5], [ 8.5, 0. , 0. , 0. , 6.5, 0. , 5.5]]) ``` Also I want the shape/structure of the array to stay the same, so I don't think Foo[np.nonzero(Foo)] is going to work... How do I do this in numpy? thanks!

Original source