2

The python code below creates data for a numpy array that I use to graph a unit box on a graph:

box = np.array([[x, y] for x in np.arange(0.0, 1.01, 0.01) for y in
               np.arange(0.0, 1.01, 0.01)])

I want to transform box -- by adding a number to the x component and a different number to the y component -- into another numpy array so the new box appears elsewhere on the graph.

I am having some trouble figuring out if I can slice a numpy array to do the addition I need or what the correct loop syntax would be.

My question is: how do I add, say 1 to each x element and 3 to each y element?

So, if some element in the initial numpy array was [0.8, 0.5], that particular element would then be (in the new array): [1.8, 3.5]. All other elements would also have their x and y values updated the same way.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Morkus
  • 517
  • 7
  • 21
  • It appears that you have never selected an answer, which means that your questions are all on the unanswered queue. You should select an answer, even for closed questions, if it helped you fix your problem. It benefits the people that put time into helping you, plus you'll get a few rep points for doing it. Select an answer by clicking on the green check box next to it. You can go through your [old questions](https://stackoverflow.com/users/5120843/morkus?tab=questions) and fix them too. – Mad Physicist Jul 02 '20 at 17:56

2 Answers2

2

You can use broadcasting. Right now you have an (n, 2) array. You can add a two element array to it directly.

offset = [1., 3.]
box2 = box + offset

This works because dimensions align on the right for broadcasting (and the list offset automatically gets converted to an array). (n, 2) broadcasts just fine with (2,).

To do the operation in-place (using same memory instead of creating a new output array):

box += offset

While you are at it, you may want to take a look at np.meshgrid and this question for examples of how to create the box much more efficiently than python list comprehensions.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
1

You can do something like this (just to explain how it works for individual columns):

# data is the array containing x,y values
 
data[:,:1] += 1 # for the first column
data[:,1:] += 3 # for the second column

print(data)
Sai Sreenivas
  • 1,690
  • 1
  • 7
  • 16