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 0 0 0 0 5 5 5 5 5 0 2 2 0 2 2 2 0 0 0 2 2 2 0 6 6 0 0 0 6 6 0 0 6 6]] 

what i want is to change the value of every none 0 number to 1.

what i can do:

for element in list: for sub_element in element: if sub_element != 0: sub_element = 1 

How can i do that in numpy?

1
  • 4
    a[a!=0] = 1 ? Commented Jun 19, 2018 at 10:55

2 Answers 2

5

If your numpy array is named a, you can use something like this:

a[a!=0.0] = 1 

proof:

>>> a = numpy.array([0.0, 1.0, 2.0, 3.0, 0.0, 10.0]) >>> a array([ 0., 1., 2., 3., 0., 10.]) >>> a[a!=0.0] = 1 >>> a array([ 0., 1., 1., 1., 0., 1.]) 

This works because a != 0.0 will return array with True/False values where the condition is met and then the assignment is performed only on those elements where there is True:

>>> a != 0 array([False, True, True, True, False, True], dtype=bool) 

Also, this works with any other condition.

Sign up to request clarification or add additional context in comments.

Comments

2

Given a NumPy array A:

res = A.astype(bool).astype(int) 

For efficiency, and most use cases, you can keep your array as Boolean, omitting the integer conversion.

This works because 0 is the only integer considered False; all others are True. Converting a Boolean array to int is then a trivial mapping of False to 0 and True to 1.

3 Comments

I checked with np.unique(A) and seems to be correct as 0 and 1 are the only values, may you edit the answer to explain how that line works as i didn't understand it, thanks.
@Nelly, Sure, I added an explanation.
@RoadRunner, I wouldn't go that far. In many cases, I think Boolean arrays are hugely underrated, you don't need the astype(int) part most times; it's true NumPy may take a byte to store a Boolean, but when you start storing large arrays in other formats (e.g. HDF5) it plays a part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.