在numpy数组中找到两个值之间的差异 [英] Finding the difference between two values in a numpy array
问题描述
我有一个由(my_array = []初始化并且形状为(0,))的numpy列表,然后将wm和hm元素附加到其上,所以(r是级联形式为-[ [300 240 22 22]]):
I have a numpy list which I initiate by (my_array=[] and has a shape of (0,)) then I append the wm and hm elements to it like so(r is a cascade with the format of-[[300 240 22 22]]):
my_array=[]
for (x, y, w, h) in r:
wm=int(x+ (w/2.))
hm=int(y+ (h/2.))
my_array.append([numpy.float32(wm), numpy.float32(hm)])
return numpy.array(my_array)
该代码产生:
wm element the hm element
[[270.01 303.43] [310.17 306.37]] # second to last row
[[269.82 303.38] [310.99 306.86]] # the last row
the shape of the returned array is (2,2) and is dtype:float32
...
现在的问题是,当我尝试附加303.43时,从理论上讲它将是[-2] [1],但索引为303.38.很好,但我还需要同时索引303.43.
Now the problem is that when I tried to append the 303.43 it theoratically would be [-2][1] but it indexes 303.38. which is fine but I also need to index 303.43 aswell.
我发现的是,第一个[]索引wm [0]或hm [1]元素,然后第二个[]索引每个元素内的两列值之一
-例如[0] [-1]索引wm元素[0]和最后一行[-1]我也想索引第二倒数第二行并尝试[0] [-2],但它没有按预期工作(它索引269.82).
What I found was that the first [] indexes either the wm[0] or hm[1] element, then the second [] indexes one of the two columns of values inside each element
-for example [0][-1] indexes the wm element[0] and last row [-1] I want to index the second last row aswell and tried [0][-2] but it didnt work as intended(it indexed the 269.82).
所以我尝试了[0] [1] [-2],但是由于IndexError:标量变量的索引无效而无法正常工作.
So I tried [0][1][-2] but it didnt work due to IndexError: invalid index to scalar variable.
我要做的就是查找wm元素中2列的最后一行与倒数第二行之间的差异(因此,在上面的示例中,它是269.82-270.1 = -0.19和303.38-303.43 =- 0.05).索引不起作用.那么有没有办法解决这个问题?
All I want to do is to find the difference between the last and second to last row for the 2 columns in the wm element(so in the example above it would be 269.82-270.1=-0.19 and 303.38-303.43=-0.05). The indexing doesn't work. So is there a way around this problem?
推荐答案
我无法重现您的数组,但鉴于您的问题(非常费解),我相信以下内容最终将满足您的要求:
I couldn't reproduce your array but given your (very convoluted) question I believe that the following will do what you ask in the end:
这应该给你269.82-270.1=-0.19
my_array[0][-2]-my_array[0][0]
这应该给你303.38-303.43=-0.05
my_array[0][-1]-my_array[0][1]
一般而言,我相信您可以按以下方式索引数组my_array
:
In general I believe that you index your array my_array
as follows:
wm element the hm element
[[my_array[0][0] my_array[0][1]] [my_array[1][0] my_array[1][1]]] # second to last row
[[my_array[0][-2] my_array[0][-1]] [my_array[1][-2] my_array[1][-1]]] # the last row
在特定情况下,倒数第二个元素也是第三个元素,因此您可以将它们索引为my_array[0][2]
而不是my_array[0][-2]
和my_array[1][2]
而不是my_array[1][-2]
In your particular case the second to last element is also the third so you could index them as my_array[0][2]
instead of my_array[0][-2]
and my_array[1][2]
instead of my_array[1][-2]
这篇关于在numpy数组中找到两个值之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!