big daddy
big daddy

Reputation: 75

Creating an array of booleans from an array of numbers

So say we have some values:

data = np.random.standard_normal(size = 10)

I want my function to output an array which identifies whether the values in data are positive or not, something like:

[1, 0, 1, 1, 0, 1, 1, 0, 0, 0]

Ive tried

def myfunc():
    for a in data > 0:
        if a:
            return 1
        else:
            return 0

But I'm only getting the boolean for the first value in the random array data, I don't know how to loop this function to ouput an array.

Thanks

Upvotes: 1

Views: 90

Answers (4)

PL200
PL200

Reputation: 741

You can use ternary operators alongside list comprehension.

data = [10, 15, 58, 97, -50, -1, 1, -33]

output = [ 1 if number >= 0 else 0 for number in data ]

print(output)

This would output:

[1, 1, 1, 1, 0, 0, 1, 0]

What's happening is that either '1' or '0' is being assigned with the logic being if the number is bigger (or equal to) 0.

If you'd like this in function form, then it's as simple as:

def pos_or_neg(my_list):
    return [ 1 if number >= 0 else 0 for number in data ]

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71610

You can do np.where, it's your friend:

np.where(data>0,1,0)

Demo:

print(np.where(data>0,1,0))

Output:

[1 0 1 1 0 1 1 0 0 0]

Do np.where(data>0,1,0).tolist() for getting a list with normal commas, output would be:

[1, 0, 1, 1, 0, 1, 1, 0, 0, 0]

Upvotes: 1

EmandM
EmandM

Reputation: 960

You are attempting to combine an if and a for statement.

Seeing as you want to manipulate each element in the array using the same criteria and then return an updated array, what you want is the map function:

 def my_func(data):
   def map_func(num):
     return num > 0

   return map(map_func, data)

The map function will apply map_func() to each number in the data array and replace the current value in the array with the output from map_func()

If you explicitly want 1 and 0, map_func() would be:

def map_func(num):
  if num > 0:
    return 1
  return 0

Upvotes: 0

berkelem
berkelem

Reputation: 2125

It's very simple with numpy:

posvals = data > 0
>> [True, False, True, True, False, True, True, False, False, False]

If you explicitly want 1s and 0s:

posvals.astype(int)
>> [1, 0, 1, 1, 0, 1, 1, 0, 0, 0]

Upvotes: 1

Related Questions