0

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?

1
  • The answer looks good, but to be sure you should give us a small example - with real values and what you expect. No one wants to display or test (20,39,90) size arrays. Also I don't see why you thing structured arrays will help you. For math you have to treat the fields as separate arrays, which you already have. Commented Jan 15, 2018 at 18:53

1 Answer 1

1

Numpy allows basic element by element arithmetic operations directly on the arrays. In addition there is whole bunch of math routines available.

Code:

The element by element division is as simple as:

result_arr = plus_arr / minus_arr

Test Code:

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)

Test Results:

[[[ 1.  1.  1.]
  [ 1.  1.  1.]]]

[[[ 3.  2.  2.]
  [ 2.  2.  2.]]]

[[[ 0.33333333  0.5         0.5       ]
  [ 0.5         0.5         0.5       ]]]
Sign up to request clarification or add additional context in comments.

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.