2

I have two arrays, each of them is composed by a pair of two integer (int1,int2). I want to compute a sum only on the first values of the pair of each array, and i want to apply a multiplication(for instance) on the second values. Clearly, if i write this code:

tab1=np.array([(1,2),(1,5),(0,6)])
tab2=np.array([(0,7),(1,4),(0,2)])
tab3=tab1+tab2
tab4=tab1*tb2

the result of tab3 will be tab3=array([[1, 9],[2, 9],[0, 8]])

The sum was applied also in the second part. but i want to obtain (1+0),(1+1),(0+0), thus: tab3=array([1,2,0])

Is it possible to have this result without do a loop on the arrays?

2 Answers 2

1

You can index to get the appropriate elements:

>>> tab1 = np.array([(1,2),(1,5),(0,6)])
>>> tab2 = np.array([(0,7),(1,4),(0,2)])
>>> tab1
array([[1, 2],
       [1, 5],
       [0, 6]])
>>> tab1[:,0]
array([1, 1, 0])
>>> tab1[:,1]
array([2, 5, 6])

and thus

>>> tab3 = tab1[:,0] + tab2[:,0]
>>> tab4 = tab1[:,1] * tab2[:,1]
>>> tab3
array([1, 2, 0])
>>> tab4
array([14, 20, 12])
Sign up to request clarification or add additional context in comments.

1 Comment

yes, it's the same procedure in Matlab for instance!!i had forgotten. thanks
0
#Calculates the adding and the multiplication
t=map((lambda x,y:(x[0]+y[0],x[1]*y[1])) , tab1,tab2)
#Splits the result
tab3,tab4 = zip(*t)

It must be noted that when using map, the loop is implicit but still occurs as internal magic.

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.