159
111

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

numpyで空配列の末尾に行を追加して2次元配列を作る

Last updated at Posted at 2016-02-02

Array

pythonのarrayは.appendメソッドを使って配列を追加することができます。

>>> arr = []
>>> arr.append([1, 2, 3])
>>> arr.append([4, 5])
>>> arr
[[1, 2, 3], [4, 5]]

行の長さが自由な2次元配列になります。

numpy.ndarray

numpyで同じように追加しようとしても2次元配列になりません。

>>> arr = np.array([])
>>> arr = np.append(arr, np.array([1, 2, 3]))
>>> arr = np.append(arr, np.array([4, 5]))
>>> arr
array([ 1.,  2.,  3.,  4.,  5.])

numpyを2次元配列として末尾に行を追加するには,以下のように書く必要があります。

>>> arr = np.empty((0,3), int)
>>> arr = np.append(arr, np.array([[1, 2, 3]]), axis=0)
>>> arr = np.append(arr, np.array([[4, 5, 0]]), axis=0)
>>> arr
array([[1, 2, 3],
       [4, 5, 0]])

ポイント

  • np.emptyで初期化しておく
  • 追加する配列の要素数は初期化した行の長さ(上の例だと3)と一致させる
  • np.appendの第二引数となるndarrayは多重配列
  • axis=0を忘れない

numpy.ndarrayの参照

>>> arr
array([[1, 2, 3],
       [4, 5, 0]])
>>> arr[0,1]
2
>>> arr[1,:2]
array([4, 5])
>>> arr[:, 1]
array([2, 5])
>>>

スライスも簡単にできて便利です。

159
111
1

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
159
111

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?