Swapping the dimensions of a numpy array

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

    I would look at numpy.ndarray.shape and itertools.product:

    import numpy, itertools
    A = numpy.ones((10,10,10,10))
    B = numpy.zeros((10,10,10,10))
    
    for i, j, k, l in itertools.product(*map(xrange, A.shape)):
        B[k,l,i,j] = A[i,j,k,l]
    

    By "without the use of loops" I'm assuming you mean "without the use of nested loops", of course. Unless there's some numpy built-in that does this, I think this is your best bet.

提交回复
热议问题