import numpy as np
a = np.array([0, 1, 2])
b = np.array([3, 4])
ans = a + b
print(ans)
実行結果
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[4], line 6
3 a = np.array([0, 1, 2])
4 b = np.array([3, 4])
----> 6 ans = a + b
8 print(ans)
ValueError: operands could not be broadcast together with shapes
(3,) (2,)
import numpy as np
a = np.array([0, 1, 2])
c = np.array([3, 4, 5])
ans = a + c
print(ans)
実行結果
[3 5 7]
import numpy as np
a = np.array([0, 1, 2])
b = np.array([3, 4])
c = np.array([3, 4, 5])
ans = np.concatenate([a, b, c])
print(ans)
実行結果
[0 1 2 3 4 3 4 5]
2次元のndarrayも連結することができます。
import numpy as np
d = np.array([[0, 1], [2, 3]])
e = np.array([[4, 5], [6, 7]])
ans = np.concatenate([d, e])
print(ans)
実行結果
[[0 1]
[2 3]
[4 5]
[6 7]]
「axis」のオプション引数を使うことで連結する軸の方向を指定することができます。
import numpy as np
d = np.array([[0, 1], [2, 3]])
e = np.array([[4, 5], [6, 7]])
ans = np.concatenate([d, e], axis=0)
print(ans)
実行結果
[[0 1]
[2 3]
[4 5]
[6 7]]
import numpy as np
d = np.array([[0, 1], [2, 3]])
e = np.array([[4, 5], [6, 7]])
ans = np.concatenate([d, e], axis=1)
print(ans)
実行結果
[[0 1 4 5]
[2 3 6 7]]
2次元以上のndarrayの場合、連結後で形が揃わない様なndarrayは連結できません。
import numpy as np
d = np.array([[0, 1], [2, 3]])
f = np.array([[4, 5, 6], [7, 8, 9]])
ans = np.concatenate([d, f], axis=0)
print(ans)
実行結果
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[22], line 6
3 d = np.array([[0, 1], [2, 3]])
4 f = np.array([[4, 5, 6], [7, 8, 9]])
----> 6 ans = np.concatenate([d, f], axis=0)
8 print(ans)
ValueError: all the input array dimensions except for the
concatenation axis must match exactly, but along dimension 1,
the array at index 0 has size 2 and the array at index 1 has size 3
もちろん形が揃っていないndarrayでも連結する方向の形が揃っている場合は連結できます。
import numpy as np
d = np.array([[0, 1], [2, 3]])
f = np.array([[4, 5, 6], [7, 8, 9]])
ans = np.concatenate([d, f], axis=1)
print(ans)
実行結果
[[0 1 4 5 6]
[2 3 7 8 9]]
コメント