Dividing elements of array Python
19,888
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)
Author by
Katey
Updated on June 14, 2022Comments
-
Katey almost 2 years
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"