0
0

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 1 year has passed since last update.

【Python】たまに苦戦するnumpy配列の結合

Last updated at Posted at 2022-04-26

使用する配列

import numpy as np

# サンプル配列の用意
# 2行5列
a = np.arange(10).reshape(2,5)
# 3行5列
b = np.arange(15).reshape(3,5)
# 2行4列
c = np.arange(8).reshape(2,4)
# 1行5列
d = list(range(5))

# 作成した配列をprintして中身を確認
print(a)
print("\n")
print(b)
print("\n")
print(c)
print("\n")
print(d)

<実行結果>
[[0 1 2 3 4]
[5 6 7 8 9]]

[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]

[[0 1 2 3]
[4 5 6 7]]

[0, 1, 2, 3, 4]

縦方向に結合

列数が同じ場合に使用できる

# 5行5列へ
e = np.vstack((a,b))
# 3行5列へ
f = np.vstack((a,d))
# 6行5列へ(3つ以上の配列の結合)
g = np.vstack((a,b,d))

print("e = np.vstack((a,b))")
print(e)
print("\nf = np.vstack((a,d))")
print(f)
print("\ng = np.vstack((a,b,d))")
print(g)

<実行結果>
e = np.vstack((a,b))
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]

f = np.vstack((a,d))
[[0 1 2 3 4]
[5 6 7 8 9]
[0 1 2 3 4]]

g = np.vstack((a,b,d))
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[ 0 1 2 3 4]]

横方向に結合

行数が同じ場合に使用できる

# 2行9列へ
h = np.hstack((a,c))

print("h = np.hstack((a,c))")
print(h)

<実行結果>
h = np.hstack((a,c))
[[0 1 2 3 4 0 1 2 3]
[5 6 7 8 9 4 5 6 7]]

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?