0
0

More than 1 year has passed since last update.

[python]hstack,vstack

Last updated at Posted at 2021-08-09

概要

pythonのhstackとvstackの使い方

どんな時に使うか

np.appendより使いやすいリストの結合方法?
pythonの標準ライブラリで

l = []
for i in range(5):
  l.append(i)
print(l)
#[0, 1, 2, 3, 4, 5]

のような処理をよく私自身が書くのだが、リストだと要素の一括削除など意外とめんどくさい
(ある要素をpopすると他の要素のインデックスも変わるため。)
その時、listで行っていた作業をnumpyで書き換えようと思うのだが、よくappendで詰まるため本記事を備忘録のため残した。

参考

この記事を見ればわかる。
https://deepage.net/features/numpy-stack.html

hstack

横方向に繋げる。
(10,)と(10,)をhstackをすると(20,)になる。

vstack

縦方向に繋げる
(10,)と(10,)をvstackすると(2, 10)になる。

サンプルプログラム

import numpy as np
a = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
b = np.arange(10, 20) # [10 11 12 13 14 15 16 17 18 19]

print(np.hstack((a,b)))
# [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

print(np.vstack((a,b)))
# [[ 0  1  2  3  4  5  6  7  8  9]
# [10 11 12 13 14 15 16 17 18 19]]
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