Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
42
Help us understand the problem. What is going on with this article?
@Umaremin

Pythonで配列や行列の結合

More than 3 years have passed since last update.

配列の結合

配列を結合するときに、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で行列の連結

42
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Umaremin

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
42
Help us understand the problem. What is going on with this article?