Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Defining a variable as a copy of another one with a condition

$
0
0

I have a variable a, that's an array, and I want to define another variable b, which is the copy of a, except for a condition (let's say, every non-zero element should be set to 1). I can write this in the following way:

>>> import numpy as np>>> a = np.array([2, 7, -2, 0, 0, 9])>>> b = np.where(a != 0, 1, 0)>>> print(b)>>> array([1, 1, 1, 0, 0, 1])

That's about fine, but I think I have encountered before the use of a simpler python notation, using no numpy, that allowed for defining b as a copy of a, but with a condition, all in one line of code, containing two equality signs, it was something like this:

b = a[a!=0]=1

The above doesn't work, but I hope you can help me find the code that I refer to or some other kind of simplification


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>