Python numpy索引不起作用

时间:2013-05-06 14:32:39

标签: python numpy

import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros((dx+dy),dtype = 'int32')
for i in np.arange(1,dy+1):
    for j in np.arange (1,dx+1):
        if i-by > 0:
            theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
            if theta<10:
                r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
                r = r.astype(int)               
                if r>0:
                    index[r]+=1
                    output = np.zeros((r, index[r]),dtype='int32')
                    output[r-1,index[r]-1] = i+(j-1)*dy

这段代码应该使用(r,index [r])作为索引,并将i +(j-1)* dy的值放到相应的索引中,并记录在一个新的矩阵/数组中,它应该像这样 - < / p>

array([[ 0,  0,  0],
   [ 0,  0,  0],
   [44,  0,  0],
   [45, 55,  0],
   [46, 56,  0],
   [47, 57,  0],
   [48, 58,  0],
   [39, 49, 59],
   [40, 50, 60]]) 

但我有这样的输出而不是我想要的 -

array([[ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0,  0],
   [ 0,  0, 60]])

1 个答案:

答案 0 :(得分:0)

很难说你的代码试图做什么。您的所需输出应该是sc还是index

或者,也许您想要创建一个新数组,我将其称为output,然后您可以使用outputs的值设置为coutput[s] = c

如果您事先不知道尺寸,那么我现在能想到的最好的事情是跟踪rowscols列表中的所有索引值,以及values列表中的实际值:

import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros(dx+dy,dtype = 'int32')
rows = []
cols = []
vals = []
for i in np.arange(2,dy+1):
    for j in np.arange(1,dx+1):
        theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
        if theta < 10:
            r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
            r = r.astype(int) 
            if r > 0:
                index[r] += 1
                rows.append(r-1)
                cols.append(index[r]-1)
                vals.append(i+(j-1)*dy)

outshape = max(rows)+1, max(cols)+1  # now you know the size
output = np.zeros(outshape, np.int)  
output[rows, cols] = vals

然后,output看起来像这样:

In [60]: output
Out[60]: 
array([[ 0,  0,  0],
       [ 0,  0,  0],
       [44,  0,  0],
       [45, 55,  0],
       [46, 56,  0],
       [47, 57,  0],
       [48, 58,  0],
       [39, 49, 59],
       [40, 50, 60]])

如果您事先知道尺寸:

import numpy as np
dx = 8
dy = 10
bx = 5.34
by = 1.09
index = np.zeros(dx+dy,dtype = 'int32')
outshape = (nrows, ncols)                        # if you know the size
output = np.zeros(outshape, np.int)              # initialize the output matrix
for i in np.arange(2,dy+1):
    for j in np.arange(1,dx+1):
        theta = 180*np.arctan(abs(j-bx)/(i-by))/np.pi
        if theta < 10:
            r = np.around(np.sqrt((j-bx)**2+(i-by)**2))
            r = r.astype(int) 
            if r > 0:
                index[r] += 1
                output[r-1, index[r]-1] = i+(j-1)*dy  # no need to set `s` or `c`