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]]