numpy.append()

numpy.append()

numpy.append()

 numpy.append()配列の末尾に要素を追加する関数 です。

numpy.append(arr, values, axis=None)

 arr には配列 (ndarray) 以外にリストやタプルなども渡せます (このような簡易表現は NumPy のコードで普通に使われます)。戻り値は必ず配列となります。

# NUMPY_APPEND

# In[1]

import numpy as np

# [1 2 3] の末尾に 99 を追加
a = np.append([1, 2, 3], 99)

print(a)
[ 1  2  3 99]

 arr が 2 次元配列のケースを見てみましょう。axis を何も指定しなければ、arr をフラット化したあとで values が追加されます。

# In[2]

# 2次元配列を定義
x = np.array([[1, 2, 3],
              [4, 5, 6]])

# xをフラット化して末尾に[7 8 9]を追加
b = np.append(x, [7, 8, 9])

print(b)
[1 2 3 4 5 6 7 8 9]

 axis=0 を指定することで、末尾の行に追加できますが、values の次元や指定軸に沿ったサイズは arr と一致していなければなりません。

# In[3]

# xの末尾の行に[7 8 9]を追加
c = np.append(x, [[7, 8, 9]], axis=0)

print(c)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

 軸に沿ったサイズが揃っていないとエラーを発生します:

# In[4]

d = np.append(x, [[7, 8, 9]], axis=1)

print(d)
ValueError:
 all the input array dimensions except for
 the concatenation axis must match exactly

 縦サイズ 2 の配列であれば、x の末尾の列に追加できます。

# In[5]

# 縦ベクトルを定義
v = np.array([[7],
              [8]])

# xの末尾の列にvを追加
e = np.append(x, v, axis=1)

print(e)
[[1 2 3 7]
 [4 5 6 8]]

【技術英語の豆知識】append は「付け足す」

 append は「付け加える、追記する」という意味の単語です。何か本体があって、それに少し付け加えるというイメージです。たとえば「文書に署名する」を "to append one's signature" と表現します。ちなみに append と同根の名詞 appendix は「付録」という意味があります。本体の末尾に付け加えられるイメージから、numpy.appned() は配列の末尾に要素を付け加える関数となっています。Python 本体にもリストの末尾に要素を追加する append() 関数が用意されています。