Reputation: 1323
Say I have an array with integers 1 through 10 and have to replace all integers less than 6 with 0 and all integers equal to or greater than 6 with 1. Currently, I am doing this:
arry[arry < 6] = 0
arry[arry >= 6] = 1
I was wondering what would be a way to combine these two statements into one line of code, or any other solution for that matter.
Upvotes: 1
Views: 2075
Reputation: 326
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(function (n) {return n >= 6 ? 1 : 0})
Upvotes: 0
Reputation: 304355
[1 if e >= 6 else 0 for e in arry]
for numpy array, (arry >= 6)
gives an array of True
/False
which you can multiply by 1
(arry >= 6) * 1
or add 0
(arry >= 6) + 0
or cast to int
(a >= 6).astype(int)
Upvotes: 1
Reputation: 1408
I assume that arry
is a numpy array (the smart indexing that you are using seems to indicate this). In that case you can simply do:
arry = (arry >= 6).astype(int)
where astype(int)
will convert the array of booleans arry >= 6
to an array of integers.
Upvotes: 5
Reputation: 19264
You can use a simple list comprehension:
array = [0 if num < 6 else 1 for num in arry]
Which is equivalent to the following loops:
temp = []
for num in arry:
if num < 6:
temp.append(0)
else:
temp.append(1)
arry = temp
Upvotes: 1
Reputation: 799082
[int(e >= 6) for e in arry]
This works because True
is defined to be the same value as 1
and False
is defined to be the same value as 0
.
Upvotes: 0