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.
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.