我想要做以下事情:
for i in dimension1:
for j in dimension2:
for k in dimension3:
for l in dimension4:
B[k,l,i,j] = A[i,j,k,l]
不使用循环。最终,A和B都包含相同的信息,但索引方式不同。
我必须指出,维度1、2、3和4可以相同也可以不同。因此,使用numpy.reshape()似乎有些困难。
我想要做以下事情:
for i in dimension1:
for j in dimension2:
for k in dimension3:
for l in dimension4:
B[k,l,i,j] = A[i,j,k,l]
不使用循环。最终,A和B都包含相同的信息,但索引方式不同。
我必须指出,维度1、2、3和4可以相同也可以不同。因此,使用numpy.reshape()似乎有些困难。
在numpy中完成此操作的规范方法是使用np.transpose
的可选排列参数。对于您的情况,从ijkl
到klij
,排列方式为(2, 3, 0, 1)
,例如:
In [16]: a = np.empty((2, 3, 4, 5))
In [17]: b = np.transpose(a, (2, 3, 0, 1))
In [18]: b.shape
Out[18]: (4, 5, 2, 3)
np.transpose
来实现这个目的。
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
您可以两次使用rollaxis
:
>>> A = np.random.random((2,4,3,5))
>>> B = np.rollaxis(np.rollaxis(A, 2), 3, 1)
>>> A.shape
(2, 4, 3, 5)
>>> B.shape
(3, 5, 2, 4)
>>> from itertools import product
>>> all(B[k,l,i,j] == A[i,j,k,l] for i,j,k,l in product(*map(range, A.shape)))
True
swapaxes
更容易理解:>>> A = np.random.random((2,4,3,5))
>>> C = A.swapaxes(0, 2).swapaxes(1,3)
>>> C.shape
(3, 5, 2, 4)
>>> all(C[k,l,i,j] == A[i,j,k,l] for i,j,k,l in product(*map(range, A.shape)))
True
product(*map(range, A.shape))
可以更简洁地写成 np.ndindex(*A.shape)
。 - Joe Kington可以利用numpy.moveaxis()
来移动所需的轴到所需的位置。以下是一个示例,借鉴自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)
np.moveaxis()
是如何将数组分割成r、b、g的?我的导师告诉我是np.split()
,但它是否隐式地与np.movieaxis
一起调用? - mLstudent33import 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]
如果你说“不使用循环”,我假设你的意思是“不使用嵌套循环”。当然,除非有一些内置的numpy函数可以实现这个需求,否则我认为这是最佳选择。
itertools.product
都是不可取的。 - user2357112