How do I use numpy's stack, vstack, and hstack?
This post contains examples of formatting numpy arrays with stack,
vstack, and hstack.
import numpy as np
Sample data
Let’s start with some normal Python lists to start.
arrays = [[i, i+1] for i in range(0, 6, 2)]
arrays
[[0, 1], [2, 3], [4, 5]]
numpy.stack
https://docs.scipy.org/doc/numpy/reference/generated/numpy.stack.html
numpy.stack is the most general of the three methods, offering an axis parameter for specifying which way to put the arrays together.
With axis 0, we end up with a shape similar to what our original Python lists were in.
stack_axis_zero = np.stack(arrays, axis=0)
stack_axis_zero, stack_axis_zero.shape
(array([[0, 1],
[2, 3],
[4, 5]]), (3, 2))
Notice how this is similar to the standard numpy.array creation from Python lists function.
np.array(arrays), np.array(arrays).shape
(array([[0, 1],
[2, 3],
[4, 5]]), (3, 2))
numpy.stack is more abstract, however, and offers an axis change as well.
stack_axis_one = np.stack(arrays, axis=1)
stack_axis_one, stack_axis_zero.shape
(array([[0, 2, 4],
[1, 3, 5]]), (3, 2))
numpy.vstack
numpy.vstack implies a vertical stack, and we end up with a similar result as above.
vertical_stack = np.vstack(arrays)
vertical_stack, vertical_stack.shape
(array([[0, 1],
[2, 3],
[4, 5]]), (3, 2))
Notice how this is similar to the more abstract numpy.stack method, operating on axis 0.
s = np.stack(arrays, axis=0)
s, s.shape
(array([[0, 1],
[2, 3],
[4, 5]]), (3, 2))
Which is also similar to creating the expected shape from numpy.array, when operating on lists.
a = np.array(arrays)
a, a.shape
(array([[0, 1],
[2, 3],
[4, 5]]), (3, 2))
numpy.hstack
nummpy.hstack is a little different, reducing the dimension and appending the arrays into one.
horizontal_stack = np.hstack(arrays)
horizontal_stack, horizontal_stack.shape
(array([0, 1, 2, 3, 4, 5]), (6,))
But it can also work on higher order dimensions.
a = np.array([[1],[2],[3]])
b = np.array([[4],[5],[6]])
c = np.array([[7],[8],[9]])
np.hstack([a, b, c])
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
Archive
chinese
tang-dynasty-poetry
李白
python
王维
rl
pytorch
numpy
emacs
杜牧
spinningup
networking
deep-learning
贺知章
白居易
王昌龄
杜甫
李商隐
tips
reinforcement-learning
macports
jekyll
骆宾王
贾岛
孟浩然
xcode
time-series
terminal
regression
rails
productivity
pandas
math
macosx
lesson-plan
helicopters
flying
fastai
conceptual-learning
command-line
bro
黄巢
韦应物
陈子昂
王翰
王之涣
柳宗元
杜秋娘
李绅
张继
孟郊
刘禹锡
元稹
youtube
visdom
system
sungho
stylelint
stripe
softmax
siri
sgd
scipy
scikit-learn
scikit
safari
research
qtran
qoe
qmix
pyhton
poetry
pedagogy
papers
paper-review
optimization
openssl
openmpi
nyc
node
neural-net
multiprocessing
mpi
morl
ml
mdp
marl
mandarin
macos
machine-learning
latex
language-learning
khan-academy
jupyter-notebooks
ios-programming
intuition
homebrew
hacking
google-cloud
github
flashcards
faker
docker
dme
deepmind
dec-pomdp
data-wrangling
craftsman
congestion-control
coding
books
book-review
atari
anki
analogy
3brown1blue
2fa