無粋な日々に

頭の中のメモ。分からないことを整理する

Python: 多次元のnumpy.arrayを1次元にするreshapeとravel

numpyの多次元配列を一次元配列にしたいときは、reshape(-1,)ravel()を使えば良い

import numpy as np

# サンプルデータ生成(3 × 3)
> x = np.arange(9).reshape(3, 3)

# 表示
> x

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

# 方法1
> x.reshape(-1,)

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


# 方法2
> np.ravel(x)

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

ねむい。ごきげんよう