import numpy as np

reshape#

行列の形を変える

x = np.arange(20)
x
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])
x = x.reshape((4,5))
x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
x.shape
(4, 5)
x2 = x.astype(np.float16)
x2
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.],
       [10., 11., 12., 13., 14.],
       [15., 16., 17., 18., 19.]], dtype=float16)
x.dtype
dtype('int64')

演習問題①#

  1. 100から119までの要素を持ったベクトルaを作る

  2. aを2x10行列に変形

  3. aを単精度浮動小数点数にキャスト変換

転置#

x2 = x.T

x2
array([[ 0,  5, 10, 15],
       [ 1,  6, 11, 16],
       [ 2,  7, 12, 17],
       [ 3,  8, 13, 18],
       [ 4,  9, 14, 19]])
x2.shape
(5, 4)

値の代入#

特定要素を置き換え

x2[0,0] = 100

x2
array([[100,   5,  10,  15],
       [  1,   6,  11,  16],
       [  2,   7,  12,  17],
       [  3,   8,  13,  18],
       [  4,   9,  14,  19]])

横ベクトルを置き換え

x2[1] = np.arange(100,104)

x2
array([[100,   5,  10,  15],
       [100, 101, 102, 103],
       [  2,   7,  12,  17],
       [  3,   8,  13,  18],
       [  4,   9,  14,  19]])

縦ベクトルを置き換え

x2[:,-1] = np.arange(1000,1005)
x2
array([[ 100,    5,   10, 1000],
       [ 100,  101,  102, 1001],
       [   2,    7,   12, 1002],
       [   3,    8,   13, 1003],
       [   4,    9,   14, 1004]])

演習問題②#

x2の0行3列目の要素を99に上書き

スライス#

複数の行をスライス

x2[0:2]
array([[ 100,    5,   10, 1000],
       [ 100,  101,  102, 1001]])

複数の列をスライス

x2[:,1:3]
array([[  5,  10],
       [101, 102],
       [  7,  12],
       [  8,  13],
       [  9,  14]])

演習問題③#

x2から2~3行目の3列目をスライス