Amr Gaballah
Amr Gaballah

Reputation: 47

setting values of np.array based on the values of another np.array python

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?

Upvotes: 0

Views: 83

Answers (2)

user2357112
user2357112

Reputation: 280291

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

Upvotes: 1

Wasi Ahmad
Wasi Ahmad

Reputation: 37691

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]

Upvotes: 0

Related Questions