Home > Enterprise >  Replacing all non-zero elements with a number in Python
Replacing all non-zero elements with a number in Python

Time:08-01

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. ]])

CodePudding user response:

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]])

CodePudding user response:

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)

CodePudding user response:

X[X !=0]=10.0 this will works for you

  • Related