2

Hello I'm a beginner programmer and I know there must be a simple way to do this but for some reason can't find the answer. I have two arrays and just want to divide each element by the elements in the other array. for example

a= np.array([2,4,6,8,10,12])
b=np.array([2,1,2,1,2,1])
so that the result is (1,4,3,8,5,12)....

I tried doing this over a for loop :

for i in range(a):
    c = a[i]/b[i]

but it doesnt work and gives the error "TypeError: only integer arrays with one element can be converted to an index"

3
  • 1
    Try a / b without the for loop, numpy does sensible things with mathematical operations on the whole array. Commented May 10, 2017 at 16:15
  • a/b will work as others have pointed out. The other problem is that you have range(a) where you should use range(len(a)). Commented May 10, 2017 at 16:39
  • @VBB yes I found out that that was my real problem, thank you! Commented May 10, 2017 at 18:45

1 Answer 1

6

You can just divide the arrays themselves (a/b)

In [1]: import numpy as np

In [2]: a = np.array([2,4,6,8,10,12])

In [3]: b = np.array([2,1,2,1,2,1])

In [4]: a/b
Out[4]: array([ 1,  4,  3,  8,  5, 12])

This happens because numpy overloads the __div__ method of the ndarray to divide the elements of the arrays and output the resulting array (the implementation is mostly in C code so it'd be difficult to link you to exactly where this happens)

Sign up to request clarification or add additional context in comments.

1 Comment

Just please, don't forget to clarify the direct division is possible due to the nature of Numpy operator overloading.

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.