0

I have a numpy array A, which contains values between 0 and 1. I want to create another numpy array y, such that the value of y(i) = 1 if A(i) >= 0.5, and y(i) = 0 if A(i) < 0.5. I used the following python code:

f=lambda v: 1 if v>0.5 else 0  
vf=np.vectorize(f)  
Y=vf(A)  

Is there a way to do this function in one line command instead of three lines?

2 Answers 2

1

Use a vectorized comparison and cast the result to int:

(A >= 0.5).astype(int)

A >= 0.5 produces an array of elementwise >= 0.5 comparison results, and astype(int) casts True to 1 and False to 0.

If you can live with single byte integers

(A >= 0.5).view(np.int8)

is a bit faster. Unlike astype view does not create new data. It reinterprets the data buffer of its operand

Sign up to request clarification or add additional context in comments.

Comments

0
import numpy

A = numpy.random.rand(10)
print(A)

Array A:

[ 0.76702953  0.89697124  0.54573644  0.48079479  0.39556016  0.50646642
  0.45998033  0.11159339  0.69824144  0.37451713]

Create another numpy array y, such that the value of y(i) = 1 if A(i) >= 0.5, and y(i) = 0 if A(i) < 0.5.

Y = (A >= 0.5).astype(int)
print(Y)

Array Y:

[1 1 1 0 0 1 0 0 1 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.