利用Python进行数据分析

数组转置和换轴

2019-01-18  本文已影响2人  庵下桃花仙

转置是一种特殊的数据重组形式,返回底层数据的视图,不需要复制任何内容。数组有 transpose 方法,也有特殊的转置属性。

In [1]: import numpy as np

In [2]: arr = np.arange(15).reshape((3, 5))

In [3]: arr
Out[3]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [4]: arr.T
Out[4]:
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])

In [5]: arr
Out[5]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [6]: arr = np.random.randn(6, 3)

In [7]: arr
Out[7]:
array([[-1.64653839, -0.52210913, -1.74885951],
       [-0.53473192, -0.27127999,  1.45919575],
       [-1.48121978,  1.41565629,  0.65597595],
       [-0.11891411,  0.26513052, -0.5896387 ],
       [ 0.16531958,  0.07125219,  0.27832976],
       [ 0.54263539, -0.51469326,  1.84498696]])

In [8]: np.dot(arr.T, arr)
Out[8]:
array([[ 5.52696324, -1.39120246,  2.24492615],
       [-1.39120246,  2.69055373,  0.35977941],
       [ 2.24492615,  0.35977941,  9.44718438]])

对于更高维的数组, transpose 方法可以接收包含轴编号的元组,用来置换轴。

In [9]: arr = np.arange(16).reshape((2, 2, 4))

In [10]: arr
Out[10]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])

In [11]: arr.transpose((1, 0, 2))
Out[11]:
array([[[ 0,  1,  2,  3],
        [ 8,  9, 10, 11]],

       [[ 4,  5,  6,  7],
        [12, 13, 14, 15]]])

用 .T 转置是换轴的特例。swapaxes 方法,接收一对轴编号作为参数,重组数据。

In [12]: arr
Out[12]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]]])

In [13]: arr.swapaxes(1, 2)
Out[13]:
array([[[ 0,  4],
        [ 1,  5],
        [ 2,  6],
        [ 3,  7]],

       [[ 8, 12],
        [ 9, 13],
        [10, 14],
        [11, 15]]])
上一篇 下一篇

猜你喜欢

热点阅读