逐列/重新调整(旋转?)N维numpy数组

时间:2016-04-07 19:57:23

标签: python numpy

我需要重塑/调整大小(数据透视?)[对不起我对numpy很新,使用它大约6周]基于专栏的numpy数组。 源numpy数组是这样的:

[[[-0.98261404]
  [-0.98261404]
  [-0.95991508]
  ..., 
  [-0.92496699]
  [-0.92731224]
  [-0.926328  ]]

 [[-0.91894622]
  [-0.91894622]
  [-0.92171439]
  ..., 
  [-1.02966519]
  [-1.03908464]
  [-1.03527072]]

 [[-0.92201427]
  [-0.92201427]
  [-0.93004196]
  ..., 
  [-1.06750448]
  [-1.07838491]
  [-1.07398661]]

 [[-0.9233676 ]
  [-0.9233676 ]
  [-0.93250255]
  ..., 
  [-1.07617807]
  [-1.08736608]
  [-1.08284474]]

 [[-0.91913077]
  [-0.91913077]
  [-0.92023803]
  ..., 
 [-1.01886934]
 [-1.02782743]
 [-1.02419806]]]

我想重塑/调整大小(pivot?)如下:

[[[-0.98261404]
  [-0.91894622]
  [-0.92201427]
  [-0.9233676 ]
  [-0.91913077]]
  ..., 
[[-0.926328  ]
 [-1.03527072]
 [-1.07398661]
 [-1.08284474]
 [-1.02419806]]]

最好的方法是什么? 谢谢!

2 个答案:

答案 0 :(得分:2)

我相信你想要的是(考虑到我确实理解它):

>>> B = np.transpose(A, (0, 2, 1))

正在A您的数据和B结果数组。这将转置/转动最后2个轴。或者,您可以写

>>> B = np.swapaxes(A, 1, 2)

等同于(并且可能更容易阅读)。扩展为N维数组:

>>> B = np.swapaxes(A, a, b) # being `a` and `b` the axes

一个例子:

>>> import numpy as np
>>> A = np.random.rand(1, 2, 3)
>>> A
array([[[ 0.54766263,  0.95017886,  0.32949198],
        [ 0.76255173,  0.88943131,  0.78594731]]])

>>> np.swapaxes(A, 1, 2)
array([[[ 0.54766263,  0.76255173],
        [ 0.95017886,  0.88943131],
        [ 0.32949198,  0.78594731]]])

或者,您可以transpose数组:

>>> A.T # equivalent to np.transpose(A, (2, 1, 0)) 
array([[[ 0.54766263],
        [ 0.76255173]],

       [[ 0.95017886],
        [ 0.88943131]],

       [[ 0.32949198],
        [ 0.78594731]]])

以相反的顺序(2, 1, 0)重新排序维度。

答案 1 :(得分:1)

假设你的数组是a

然后这应该可以解决问题:

x,y,z = a.shape
b = a.T #Transpose - get the indices grouped along the other axis
b = b.reshape(y, x, z) #Interchange the axes.

例如:

In [58]: a = np.random.random(20)

In [59]: a = a.reshape(4,5,1)

In [60]: a
Out[60]: 
array([[[ 0.40906066],
        [ 0.57160002],
        [ 0.22642471],
        [ 0.35845352],
        [ 0.26999423]],

       [[ 0.91962882],
        [ 0.62664991],
        [ 0.21286972],
        [ 0.39995373],
        [ 0.1141539 ]],

       [[ 0.03040894],
        [ 0.79666903],
        [ 0.72822631],
        [ 0.84388555],
        [ 0.23265895]],

       [[ 0.63548896],
        [ 0.50314843],
        [ 0.88547892],
        [ 0.49824574],
        [ 0.55835843]]])

In [61]: b = b.reshape(y, x, z)

In [62]: x,y,z = a.shape

In [63]: b = a.T

In [64]: b = b.reshape(y,x,z)

In [65]: b
Out[65]: 
array([[[ 0.40906066],
        [ 0.91962882],
        [ 0.03040894],
        [ 0.63548896]],

       [[ 0.57160002],
        [ 0.62664991],
        [ 0.79666903],
        [ 0.50314843]],

       [[ 0.22642471],
        [ 0.21286972],
        [ 0.72822631],
        [ 0.88547892]],

       [[ 0.35845352],
        [ 0.39995373],
        [ 0.84388555],
        [ 0.49824574]],

       [[ 0.26999423],
        [ 0.1141539 ],
        [ 0.23265895],
        [ 0.55835843]]])