Fraz Fraz - 1 year ago 84
Python Question

Better way to vectorize using numpy

I am wondering if there is a better way to vectorize the following:

array = []
for ele in long_list:
if condition:
vector = np.array(array)

Now this is essentially
except for that

Is there a better (vectorized) way of achieving the above?

Answer Source
vector = np.fromiter((1 for ele in long_list if condition), dtype=int)

This should be faster than either:

vector = np.ones(len([x for x in long_list if conditon]))


vector = np.array( [1 for ele in long_list if condition(ele)] )

because it avoids building the filtered list, due to the fact that (1 for ele in long_list if condition) returns a generator not a list.


I'm wondering if this isn't also a viable option:

vector = np.array( (1 for ele in long_list if condition(ele)) )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download