Replacing all non-zero elements with a number in Python

Question:

I want to replace all non-zero elements of the array X with 10. Is there a one-step way to do so? I present the expected output.

import numpy as np
X=np.array([[10.                 ,  0.6382821834929432 ,  0.5928417218382795 ,
        0.5542698411479658 ,  0.                 ,  0.6677634679746701 ,
        0.8578897621707481 ,  0.                 ,  0.6544597670890333 ,
        0.32706383813570833,  0.                 ,  0.8966468940380192 ]])

The expected output is

X=array([[10.,  10. ,  10. ,
        10. ,  0.,  10.,
        10. ,  0.,  10.,
        10.,  0.,  10. ]])
Asked By: user19657580

||

Answers:

Use numpy.where:

X2 = np.where(X!=0, 10, 0)

Or, for in place modification:

X[X!=0] = 10

For fun, a variant using equivalence of True/False and 1/0:

X2 = (X!=0)*10

Output:

array([[10, 10, 10, 10,  0, 10, 10,  0, 10, 10,  0, 10]])
Answered By: mozway

You can consider using numpy.putmask

Here is an example for your solution

import numpy as np

X=np.array([[10.                 ,  0.6382821834929432 ,  0.5928417218382795 ,
        0.5542698411479658 ,  0.                 ,  0.6677634679746701 ,
        0.8578897621707481 ,  0.                 ,  0.6544597670890333 ,
        0.32706383813570833,  0.                 ,  0.8966468940380192 ]])

np.putmask(X, X != 0, 10)

Answered By: Addy
X[X !=0]=10.

this will works for you

Answered By: Rajeev Yadav
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.