Python 调换数组维度的一些注意事项

Python 调换数组维度的一些注意事项

import numpy as np

随机一个多维数组

a = np.random.randint(0,10,(2,3,4,5))
print(a)
[[[[5 3 2 0 5]
   [5 3 0 3 6]
   [3 1 3 8 3]
   [2 3 9 0 6]]

  [[7 1 6 2 3]
   [2 2 4 7 6]
   [4 1 3 4 0]
   [1 2 0 2 1]]

  [[2 8 4 2 7]
   [5 9 1 8 1]
   [0 0 1 9 3]
   [1 8 0 1 5]]]


 [[[0 7 8 8 2]
   [6 6 1 7 1]
   [4 0 2 6 3]
   [4 6 5 5 4]]

  [[1 4 8 0 0]
   [9 9 3 4 7]
   [3 6 9 2 0]
   [2 3 6 4 3]]

  [[3 8 6 5 2]
   [8 8 4 8 7]
   [1 9 0 2 2]
   [6 9 9 8 2]]]]

现在想要将数组维度改变为(2,3,4,5)->(4,3,5,2)

使用reshape函数改变维度

b = np.reshape(a,(4,3,5,2))

比较二者差异

import itertools as IT    
all(b[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, b.shape)))
False

使用Einstein summation convention

c = np.einsum('qjip->ijpq',a)
all(c[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, c.shape)))
True

使用transpose

d = np.transpose(a,(2,1,3,0))
all(d[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, d.shape)))
True

换用不同的order

b1 = np.reshape(a,(4,3,5,2),order='C')
b2 = np.reshape(a,(4,3,5,2),order='A')
b3 = np.reshape(a,(4,3,5,2),order='F')
for array in [b1,b2,b3]:
    print(all(array[i,j,p,q] == a[q,j,i,p] for i,j,p,q in IT.product(*map(range, array.shape))))
False
False
False

总结一句话就是,别用reshape!!!

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值