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

查看:267
本文介绍了交换 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天全站免登陆