将2D numpy数组重组为3D
我有一个12X2阵列,我想重新组织成3x4x2阵列.具体来说,我想更改
I have a 12X2 array I want to reorganize into a 3x4x2 array. Specifically, I want to change
a = np.array(([1,13],[2,14],[3,15],[4,16],[5,17],[6,18],[7,19],[8,20],[9,21],[10,22],[11,23],[12,24]))
[[ 1 13]
[ 2 14]
[ 3 15]
[ 4 16]
[ 5 17]
[ 6 18]
[ 7 19]
[ 8 20]
[ 9 21]
[10 22]
[11 23]
[12 24]]`
插入一个看起来像这样的矩阵:
Into a matrix that looks like this:
[[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
[[ 13. 14. 15. 16.]
[ 17. 18. 19. 20.]
[ 21. 22. 23. 24.]]]
我当时在想三重嵌套的for循环,但是我编码的方式行不通.而且我无法将自己的头围在numpy索引周围,以至于无法确定如何做到这一点.
I was thinking a triple-nested for loop, but the way I coded it is not going to work. And I can't wrap my head around numpy indexing enough to figure out how to do this.
这当然是示例代码.我想对此进行更改,以便在纬度-经度网格上绘制全球降水的前3个EOF的3个图.从8192x8192阵列中拉出EOF,并放入64x128x3阵列中. (我仅使用大型矩阵的前三列.每一列都是EOF,在每一列的下方,值均按沿第一个纬度的经度列出,然后按沿第二个纬度的经度列出,依此类推向下直到该列底部的第128个纬度.当然,由于第一个纬度为-87.something,我的数组在完成后相对于底图将上下颠倒,但是我打算使用np.flipud来完成后将其修复.
This is of course example code. I want to alter this for use to make 3 plots of the leading 3 EOFs of global precipitation on a latitude-longitude grid. The EOFs are being pulled from a 8192x8192 array and put into a 64x128x3 array. (I'm only using the first 3 columns of the large matrix. Each column is an EOF, and down each one, values are listed by longitude going along the first latitude, then listed by longitude again going along the second latitude, and so on down until the 128th latitude at the bottom of the column. Of course my array will be upside-down with respect to the base map when I finish since the first latitude is -87.something, but I plan to use np.flipud to fix it once it's finished.
您可以结合使用 np.transpose
,就像这样-
You can use a combination of np.reshape
and np.transpose
, like so -
a.reshape(3,4,-1).transpose(2,0,1)
所以,对于您的实际情况(如果我理解正确的话)是-
So, for your actual case (if I understood it correctly) would be -
a.reshape(64,128,-1).transpose(2,0,1)
请注意,在这种情况下,输出形状将为(3, 64, 128)
.因此,我假设示例案例与您的实际案例不正确.
Please note that the output shape in this case would be (3, 64, 128)
though. So, I am assuming the sample case doesn't properly correspond to your actual case.