Posted at

numpyの配列操作備忘録

More than 1 year has passed since last update.

numpyの行列操作をすぐ忘れるので見返すための備忘録


テストデータの作成

# 要素が0の行列 np.zeros(shape)

## 0が10個の配列
In [16]: np.zeros(10)
Out[16]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

## 2行2列で要素が0の行列
In [17]: np.zeros((2,2))
Out[17]:
array([[ 0., 0.],
[ 0., 0.]])

# 配列の作成 np.arange(start, stop, step)
## 0から9まで1ずつ増える配列
In [19]: np.arange(10)
Out[19]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

## 1から9まで1ずつ増える配列
In [20]: np.arange(1, 10)
Out[20]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])

## 1から9まで2ずつ増える配列
In [21]: np.arange(1, 10, 2)
Out[21]: array([1, 3, 5, 7, 9])

# 配列を行列に変換 reshape(new_shape)
## 1~9の配列を3x3の行列に変換
In [23]: np.arange(1,10).reshape((3,3))
Out[23]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])


行列から特定のデータの取得

# 1箇所指定して取得

## 1次元の場合 x[index]
In [26]: x = np.arange(10)

In [27]: x
Out[27]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [28]: x[3]
Out[28]: 3

In [29]: x[-1]
Out[29]: 9

## 多次元の場合 x[index1, index2, ...]
In [31]: x = np.arange(25).reshape((5,5))

In [32]: x
Out[32]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])

In [33]: x[1, 2]
Out[33]: 7

In [34]: x[-1, -2]
Out[34]: 23

# 範囲を指定して取得

## 1次元の場合 x[start:stop:step]
In [36]: x = np.arange(10)
In [41]: x
Out[41]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [40]: x[1:10]
Out[40]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])

In [39]: x[1:10:2]
Out[39]: array([1, 3, 5, 7, 9])

## 多次元の場合 x[start1:stop1:step1, start2:stop2,step2, ...]
In [42]: x = np.arange(25).reshape((5,5))

In [43]: x
Out[43]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])

In [45]: x[1:-1, 1:3]
Out[45]:
array([[ 6, 7],
[11, 12],
[16, 17]])

参考:

http://wbhappy.hatenablog.jp/entry/2015/02/06/210000

https://qiita.com/supersaiakujin/items/d63c73bb7b5aac43898a