Swapping the dimensions of a numpy array

前端 未结 5 1770
不思量自难忘°
不思量自难忘° 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:28

    Please note: Jaime's answer is better. NumPy provides np.transpose precisely for this purpose.


    Or use np.einsum; this is perhaps a perversion of its intended purpose, but the syntax is quite nice:

    In [195]: A = np.random.random((2,4,3,5))
    
    In [196]: B = np.einsum('klij->ijkl', A)
    
    In [197]: A.shape
    Out[197]: (2, 4, 3, 5)
    
    In [198]: B.shape
    Out[198]: (3, 5, 2, 4)
    
    In [199]: import itertools as IT    
    In [200]: all(B[k,l,i,j] == A[i,j,k,l] for i,j,k,l in IT.product(*map(range, A.shape)))
    Out[200]: True
    

提交回复
热议问题