56
54

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.

Pythonで配列や行列の結合

Last updated at Posted at 2018-03-21

配列の結合

配列を結合するときに、appendとextendが使える。
これらは、それぞれ結果が異なる。

unite_list_1.py

a = [1,2,3]
b = [4, 5]

# appendで要素を結合
a1 = a
a1.append(4)
print(a1) # [1, 2, 3, 4]

# appendで配列を結合すると、結合した配列が入れ子になる
a1 = a
a1.append(b)
print(a1) # [1, 2, 3, [4, 5]] 

# extendなら、配列が入れ子にならない
a1 = a
a1.extend(b)
print(a1) # [1, 2, 3, 4, 5]

2次元配列を結合したときの結果

unite_list_2.py
a=[[1,2,3],[4,5,6]]
b=[[7,8],[9,10]]

#appendで配列を結合すると、やっぱり入れ子になる
a1 = a
a1.append(b)
print(a1) # [[1, 2, 3], [4, 5, 6], [[7, 8], [9, 10]]]

#extendで結合すると、入れ子にならない
a1 = a
a1.extend(b)
print(a1) # [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]

行列の結合

配列の結合はできたものの、行列の結合のような操作は少し面倒になる。

unite_list_3.py
a=[[1,2,3],[4,5,6]]
b=[[7,8],[9,10]]
a1 = a

for i in range(2):
    a1[i].extend(b[i])

print(a1) # [[1, 2, 3, 7, 8], [4, 5, 6, 9, 10]]

そこで、Numpyを使うと簡単にできる。たとえば、行列を列を増やす方向に結合の場合:

numpy_1.py
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[7,8],[9,10]])

c = np.concatenate((a,b), axis = 1) 
print(c)

#または

c = np.c_[a,b]
print(c)

#または

c = np.hstack([a,b])
print(c)

# 結果:
#  [[ 1  2  3  7  8]
#  [ 4  5  6  9 10]]

行を増やす方向の結合:

numpy_1.py
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[7,8],[9,10]])

c = np.concatenate((a.T,b), axis = 0) 
print(c)

#または

c = np.r_[a.T,b]
print(c)

#または

c = np.vstack([a.T,b])
print(c)

# 結果:
# [[ 1  4]
#  [ 2  5]
#  [ 3  6]
#  [ 7  8]
#  [ 9 10]]

Numpyを使う場合でも、行数、列数が合っていないとエラーになるので注意は必要。

環境

Windows10 64bit
Python 3.6.4
Conda 4.4.11 (Anaconda 3)

参照

Numpyで行列の連結

56
54
0

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
56
54

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?