user1879926
user1879926

Reputation: 1323

Assign 0 and 1 based on values greater than in one line

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

Answers (6)

huwence
huwence

Reputation: 326

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(function (n) {return n >= 6 ? 1 : 0})

Upvotes: 0

John La Rooy
John La Rooy

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

Thibaut
Thibaut

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

A.J. Uppal
A.J. Uppal

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

J0HN
J0HN

Reputation: 26941

list(map(lambda i: 0 if i<6 else 1, a))

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

Related Questions