1

So, I have a given 2 dimensional matrix which is randomly generated:

a = np.random.randn(4,4)

which gives output:

array([[-0.11449491, -2.7777728 , -0.19784241,  1.8277976 ],
   [-0.68511473,  0.40855461,  0.06003551, -0.8779363 ],
   [-0.55650378, -0.16377137,  0.10348714, -0.53449633],
   [ 0.48248298, -1.12199767,  0.3541335 ,  0.48729845]])

I want to change all the negative values to 0 and all the positive values to 1. How can I do this without a for loop?

2 Answers 2

1

You can use np.where()

import numpy as np

a = np.random.randn(4,4)
a = np.where(a<0, 0, 1)

print(a)

[[1 1 0 1]
 [1 0 1 0]
 [1 1 0 0]
 [0 1 1 0]]
Sign up to request clarification or add additional context in comments.

Comments

1
(a<0).astype(int)

This is one possibly solution - converting the array to boolean array according to your condition and then converting it from boolean to integer.

array([[ 0.63694991, -0.02785534,  0.07505496,  1.04719295],
   [-0.63054947, -0.26718763,  0.34228736,  0.16134474],
   [ 1.02107383, -0.49594998, -0.11044738,  0.64459594],
   [ 0.41280766,  0.668819  , -1.0636972 , -0.14684328]])

And the result -

(a<0).astype(int)
>>> array([[0, 1, 0, 0],
          [1, 1, 0, 0],
          [0, 1, 1, 0],
          [0, 0, 1, 1]])

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.