简体   繁体   English

如何为两列 numpy 数组中的所有坐标添加偏移量?

[英]How to add offset to all coordinates in a two-column numpy array?

The python code below creates data for a numpy array that I use to graph a unit box on a graph:下面的 python 代码为 numpy 数组创建数据,我用它在图表上绘制单位框:

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.我想将box (通过向 x 分量添加一个数字,向 y 分量添加一个不同的数字)转换为另一个 numpy 数组,以便新框出现在图表的其他位置。

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.我无法确定是否可以对 numpy 数组进行切片以进行我需要的添加或正确的循环语法是什么。

My question is: how do I add, say 1 to each x element and 3 to each y element?我的问题是:如何向每个 x 元素添加 1,向每个 y 元素添加 3?

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] .因此,如果初始 numpy 数组中的某个元素是[0.8, 0.5] ,那么该特定元素将是(在新数组中): [1.8, 3.5] All other elements would also have their x and y values updated the same way.所有其他元素也将以相同的方式更新其 x 和 y 值。

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.现在你有一个(n, 2)数组。 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).这是有效的,因为尺寸在右侧对齐以进行广播(并且列表offset自动转换为数组)。 (n, 2) broadcasts just fine with (2,) . (n, 2)(2,) ) 广播就好了。

To do the operation in-place (using same memory instead of creating a new output array):就地执行操作(使用相同的 memory 而不是创建新的 output 数组):

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.当您使用它时,您可能想查看np.meshgrid这个问题,以了解如何比 python 列表理解更有效地创建框的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM