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!
nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .
While the nonzero values can be obtained with a[nonzero(a)] , it is recommended to use x[x. astype(bool)] or x[x != 0] instead, which will correctly handle 0-d arrays. A common use for nonzero is to find the indices of an array, where a condition is True.
save() numpy. save() function is used to store the input array in a disk file with npy extension(. npy).
Therefore, we can save the NumPy arrays into a native binary format that is efficient to both save and load. This is common for input data that has been prepared, such as transformed data, that will need to be used as the basis for testing a range of machine learning models in the future or running many experiments.
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]])
you can also do it in place as follows
>>> import numpy as np
>>> 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]])
>>> foo[foo!=0] += 5
>>> foo
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]])
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With