2

I am not quite sure how to describe my question, but I will try.

I want to know if numpy has the functionality to do this:

Lets say I have a 2D array called grid:

grid = [ [0,0],
         [0,0] ]

I also have a second 2D array called aList:

aList = [ [1,2],
          [3,4] ]

I want to apply math to the first array based on the index of the first array.

So the math done at each iteration would look like this:

grid[i][j] = [(i - aList[k][0]) + (j - aList[k][1])] 

Currently doing this in python with for loops is way to expensive so I need an alternative.

EDIT: more clarification, if I were not to use numpy I would write something like this:

for i in range(2):
    for j in range(2):
        num = 0 
        for k in range(2):
            num += (i-aList[k][0]) + (j-aList[k][1])
        grid[i][j] = num

This is however way to slow in python for the amount of data I have.

4
  • 1
    Could you please paste a small working copy of your script? It is hard to parse what is going on here. What is k? Commented Jul 2, 2013 at 19:17
  • If this is really what you are doing, and k is the iteration number, then notice that your expression can be simplified to [i + j - c] where c = aList[k][0] + aList[k][1]... Commented Jul 2, 2013 at 19:19
  • Sorry if I made this confusing, I knew I was going to be bad at explaining this. i, j, and k are all iterators. i and j are iterating over the entire 2D array grid. K is iterating over the array, aList at each spot in grid. Commented Jul 2, 2013 at 19:32
  • 1
    Can you please post your current code using for loops. This is very likely something numpy can help with. Commented Jul 2, 2013 at 19:36

1 Answer 1

1

Your code can be reproduced and substantially sped up as follows:

i_s = np.arange(2)
j_s = np.arange(2)

fast_grid = (i_s + j_s[:, None])*len(aList) - aList.sum()
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.