python creating new list using a “template list”
4
Suppose i have:
x1 = [1, 3, 2, 4]
and:
x2 = [0, 1, 1, 0]
with the same shape
now i want to "put x2 ontop of x1" and sum up all the numbers of x1 corresponding to the numbers of x2
so the end result is:
end = [1+4 ,3+2] # end[0] is the sum of all numbers of x1 where a 0 was in x2
this is a naive implementation using list to further clarify the question
store_0 = 0
store_1 = 0
x1 = [1, 3, 4, 2]
x2 = [0, 1, 1, 0]
for value_x1 ,value_x2 in zip(x1 ,x2):
if value_x2 == 0:
store_0 += value_x1
elif value_x2 == 1:
store_1 += value_x1
so my question: is there is a way to implement this in numpy without using loops or in general just faster?
python numpy
New contributor
user15770670 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
x2==1
returns a set of true/false values that can be used to filter other operations. So,x1[x2==0].sum()
andx1[x2==1].sum()
do the two operations you have there. – Tim Roberts Apr 26 at 18:59