Reputation: 1471
I am new to structured arrays, but I think it is that what I need.
I have a numpy array which contains for every entry a minus counter and one array that contains a plus counter. They are filled within a process. At the end of this process I want to divide all plus counter cell per cell through the minus counter and save it in an array with the result of this calculation in every entry.
So I think there is a better way to create three different arrays with the same size. Lets assume my arrays are in this form:
import numpy as np
import itertools
plusArr = np.ones((20 ,39, 90))
minusArr = np.ones((20 ,39, 90))
resultArr = np.zeros((20 ,39, 90))
Then the cells are filled with numbers. At the end I doing something like:
for i in itertools.product(np.arange(0,20,1),np.arange(0,39,1),np.arange(0,90,1)):
resultArr[i[0]][i[1]][i[2]] = plusArr[i[0]][i[1]][i[2]]/minusArr[i[0]][i[1]][i[2]]
print(resultArr)
This works but in the filling process it is very time consuming to look up the same entry location for both, minus and plus array. So I thought maybe to have a structured array with a triple instead of i
int entries. In every triple the first entry is the plus counter, the second is the minus counter, and the last entry is 0 until the filling process is finished and it can be filled with the result of the division of plus and minus entry.
As a small side question. If one of my counter entries is 0, then i want to fill the result cell of the entry of the array which has no zero entry at this location. Is there a smart numpy way to do that or just an if condition?
Upvotes: 0
Views: 46
Reputation: 49812
Numpy allows basic element by element arithmetic operations directly on the arrays. In addition there is whole bunch of math routines available.
The element by element division is as simple as:
result_arr = plus_arr / minus_arr
import numpy as np
size = (1, 2, 3)
plus_arr = np.ones(size)
minus_arr = np.ones(size) * 2
minus_arr[0, 0, 0] = 3
result_arr = plus_arr / minus_arr
print(plus_arr)
print(minus_arr)
print(result_arr)
[[[ 1. 1. 1.]
[ 1. 1. 1.]]]
[[[ 3. 2. 2.]
[ 2. 2. 2.]]]
[[[ 0.33333333 0.5 0.5 ]
[ 0.5 0.5 0.5 ]]]
Upvotes: 1