Swapping the dimensions of a numpy array

前端 未结 5 1787
不思量自难忘°
不思量自难忘° 2020-12-09 14:37

I would like to do the following:

for i in dimension1:
  for j in dimension2:
    for k in dimension3:
      for l in dimension4:
        B[k,l,i,j] = A[i,j,         


        
5条回答
  •  旧巷少年郎
    2020-12-09 15:14

    One can also leverage numpy.moveaxis() for moving the required axes to desired locations. Here is an illustration, stealing the example from Jaime's answer:

    In [160]: a = np.empty((2, 3, 4, 5))
    
    # move the axes that are originally at positions [0, 1] to [2, 3]
    In [161]: np.moveaxis(a, [0, 1], [2, 3]).shape 
    Out[161]: (4, 5, 2, 3)
    

提交回复
热议问题