交换numpy数组的维数 [英] Swapping the dimensions of a numpy array

查看:92
本文介绍了交换numpy数组的维数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行以下操作:

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都包含相同的信息,但已对其进行了索引 不一样.

without the use of loops. In the end both A and B contain the same information but indexed differently.

我必须指出,尺寸1,2,3和4可以相同或不同.所以numpy.reshape()似乎很困难.

I must point out that the dimension 1,2,3 and 4 can be the same or different. So a numpy.reshape() seems difficult.

推荐答案

请注意: Jaime的答案更好. NumPy正是为此目的提供了np.transpose.

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

或使用 np.einsum ;这也许是其预期目的的一个变态,但是语法非常不错:

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

这篇关于交换numpy数组的维数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆