[英]extracting ith and ith+1 from random 2D numpy array
I have a numpy array consisting of 我有一个由
[1,3,8,6,0,2,4,5,9,7]
This array is a random array consisting of 10 numbers 0-9. 此数组是由10个数字0-9组成的随机数组。
I also have a 2D numpy array, a 10X10 2D numpy array with numerical values. 我也有一个2D numpy数组,一个带有数值的10X10 2D numpy数组。
I would like to use my 1D numpy array (above) to access specific instances in my 2D numpy array, by looping through the 1D array 我想使用我的1D numpy数组(如上)通过遍历1D数组来访问2D numpy数组中的特定实例。
. 。
I would like to add up these values in my 2D numpy array. 我想将这些值加到我的2D numpy数组中。
so far I have : array=[1,3,8,6,0,2,4,5,9,7] 到目前为止,我有:array = [1,3,8,6,0,2,4,5,9,7]
values =0
for i in range (0, len(array)): #this is 10
a=array2[i,array[i]+1] #array2 is the 2D numpy array with the values
values=values+a
This works to some degree but how to I get it to access the last element to the first? 这在某种程度上有效,但是如何获取最后一个元素到第一个元素呢? ie find [7,1]
即找到[7,1]
You can do the slicing twice to make it work. 您可以进行两次切片以使其起作用。
values = 0
for i in range(len(array)):
a = Matrix[array[i],array[i+1]]
values += a
Also, the array you put has 11 elements which means the 10-th loop will not be what you intended. 另外,您放置的数组有11个元素,这意味着第10个循环将不是您想要的。
You can use simple slicing to make this work. 您可以使用简单的切片来完成这项工作。
arr = np.random.randint(0, 10, (10,10))
pos = np.array([1,3,8,6,0,2,4,5,9,7])
pos = np.append(pos, pos[0])
rows = pos[0:-1]
cols = pos[1:]
result = sum(arr[rows, cols])
I'm not sure I fully understood what you were trying to achieve but... What about something like this? 我不确定我是否完全理解您要达到的目标,但是……类似的事情呢?
a = np.array([1,3,8,6,0,9,2,4,5,9,7])
b = np.array(range(100)).reshape(10,10)
for i in range (len(a)):
print (a[i%len(a)],a[(i+1)%len(a)])
print (b[a[i%len(a)],a[(i+1)%len(a)]])
I removed 10 from the a
array to avoid an index out of range error. 我从
a
数组中删除了10个,以避免索引超出范围错误。
I also took the value [x,y] (and not the range [x:y] from the 2D array. 我还从二维数组中获取了值[x,y](而不是范围[x:y])。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.