1

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

1
  • Feel free to accept your favorite answer. This benefits both you and the answerer, and makes it easier for anyone who has the same question in the future. Commented Oct 6, 2018 at 8:05

4 Answers 4

1

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

1

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 ]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.