LoginSignup
12
14

More than 5 years have passed since last update.

[Python]Numpyデータの行と列の入れ替え

Posted at

前提

全てにおいて下記を実行しているとする

import numpy as np

3x3行列の作成

arr = np.arange(9).reshape((3,3))

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

行列の転置

arr.T

array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])
行と列を入れ替えるtranspose
arr.transpose()

array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])
arr.transpose((1,0))

array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])
軸を入れ替えるsapaxes

2つの軸に関して入れ替えるときに使用

arr.swapaxes(1,0)

array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])

arr.swapaxes(0,1)

array([[0, 3, 6],
       [1, 4, 7],
       [2, 5, 8]])

行列の掛け算

np.dot(arr.T,arr)

array([[45, 54, 63],
       [54, 66, 78],
       [63, 78, 93]])

3次元の行列入れ替え

2x2の行列が3つ積み上がってる

arr3d = np.arange(12).reshape((3,2,2)) 
arr3d

array([[[ 0,  1],
        [ 2,  3]],

       [[ 4,  5],
        [ 6,  7]],

       [[ 8,  9],
        [10, 11]]])

arr3d[0]

array([[0, 1],
       [2, 3]])
3次元行列にたいしてtransposeを使ってみる

第1引数:0 → 2x2の行列が3つ積み上がっていることに対してはなにもしない
第2引数:2 → 2x2の行列の転置
第3引数:1 → 2x2の行列の転置

arr3d.transpose((0,2,1))

array([[[ 0,  2],
        [ 1,  3]],

       [[ 4,  6],
        [ 5,  7]],

       [[ 8, 10],
        [ 9, 11]]])
12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14