user19657580
user19657580

Reputation: 39

Replacing all non-zero elements with a number in Python

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

Upvotes: 1

Views: 1110

Answers (3)

Rajeev Yadav
Rajeev Yadav

Reputation: 23

X[X !=0]=10.

this will works for you

Upvotes: 1

Addy
Addy

Reputation: 166

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)

Upvotes: 2

mozway
mozway

Reputation: 262234

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

Upvotes: 5

Related Questions