Reputation: 530
if I have for example a vector like
import numpy as np
a=np.array([1,2,-3,4,-5])
if I want to create a vector b
with the negative values of a
I can of course do a for
loop
list=[]
for i in a:
if i<0:
list.append(i)
b=np.array(list)
but I am sure that there is a better way. What is a more synthetic, python-ish way to do the same thing?
Upvotes: 0
Views: 71
Reputation: 3985
Arrays are inherently able to be selected by a boolean array, so:
a=np.array([1,2,-3,4,-5])
b=a[a<0]
Gives
>>> b
array([-3, -5])
Upvotes: 2
Reputation: 5958
You can try with list comprehension:
b = np.array([i for i in a if i < 0])
Upvotes: 1