切片3D数组numpy

时间:2020-08-21 00:32:38

标签: python arrays numpy

请考虑以下内容:

In[1]: pos
Out[1]:
array([[0, 1, 2, 3],
       [2, 3, 4, 5],
       [0, 1, 6, 7],
       [2, 3, 6, 7],
       [2, 3, 8, 9],
       [4, 5, 8, 9],
       [6, 7, 8, 9]])

In[2]: pos = pos.reshape((7,1,4))
Out[2]:
array([[[0, 1, 2, 3]],
       [[2, 3, 4, 5]],
       [[0, 1, 6, 7]],
       [[2, 3, 6, 7]],
       [[2, 3, 8, 9]],
       [[4, 5, 8, 9]],
       [[6, 7, 8, 9]]])

In[3]: af = np.zeros((7,10,4))

我想按照以下循环在af数组的特定位置处替换:

for i in range(7):
    af[i,pos[i],pos[0]] = 1

有了这个,我想知道是否有任何方法可以无循环地进行这种替换。

1 个答案:

答案 0 :(得分:1)

In [391]: pos = np.array([[0, 1, 2, 3], 
     ...:        [2, 3, 4, 5], 
     ...:        [0, 1, 6, 7], 
     ...:        [2, 3, 6, 7], 
     ...:        [2, 3, 8, 9], 
     ...:        [4, 5, 8, 9], 
     ...:        [6, 7, 8, 9]])                                                                      
In [392]: af = np.zeros((7,10,4),int)                                                                
In [393]: for i in range(7): 
     ...:     af[i,pos[i],pos[0]] = 1 
     ...:                                                                                            

pos重塑有什么区别吗?

In [395]: pos1 = pos.reshape((7,1,4))                                                                
In [398]: af1 = np.zeros((7,10,4),int)                                                                                                                                                           
In [399]: for i in range(7): 
     ...:     af1[i,pos1[i],pos1[0]] = 1 
     ...:      
     ...:                                                                                            
In [400]: np.allclose(af,af1)                                                                        
Out[400]: True

不,让我们忘记它。

我评论过x[np.arange(n), idx]是分配诸如循环之类的值的常用方法。索引数组需要相互广播以定义所需的元素。

如果我们尝试:

In [403]: af[np.arange(7),pos,pos[0]]                                                                
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-403-6488d02c6898> in <module>
----> 1 af[np.arange(7),pos,pos[0]]

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (7,) (7,4) (4,) 

因此,使第一个索引为(7,1)形状:

In [404]: af[np.arange(7)[:,None],pos,pos[0]]                                                        
Out[404]: 
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
In [405]: af2 = np.zeros((7,10,4),int)                                                               
In [406]: af2[np.arange(7)[:,None], pos,pos[0]] = 1                                                  
In [407]: np.allclose(af,af2)                                                                        
Out[407]: True
相关问题