How do I stack column-wise n vectors of shape (x,) where x could be any number?
For example,
from numpy import *
a = ones((3,))
b = ones((2,))
c = vstack((a,b)) # <-- gives an error
c = vstack((a[:,newaxis],b[:,newaxis])) #<-- also gives an error
hstack works fine but concatenates along the wrong dimension.
Short answer: you can’t. NumPy does not support jagged arrays natively.
Long answer:
gives an array that may or may not behave as you expect. E.g. it doesn’t support basic methods like
sumorreshape, and you should treat this much as you’d treat the ordinary Python list[a, b](iterate over it to perform operations instead of using vectorized idioms).Several possible workarounds exist; the easiest is to coerce
aandbto a common length, perhaps using masked arrays or NaN to signal that some indices are invalid in some rows. E.g. here’sbas a masked array:This can be stacked with
aas follows:(For some purposes,
scipy.sparsemay also be interesting.)