Clemens Clemens - 7 months ago 245
Python Question

Python zip numpy arrays of different dimension

I'd like to zip numpy arrays befor saving it via
. For zipping one dimensional arrays I use

import numpy as np

a = np.ones(4) * 5.
b = np.ones(4) * 4.
data = np.array(zip(a, b))

which does exactly what I want. Now I have more data, say like

c = numpy.ones((2, 4))


data = np.array(zip(a, b, c))

does not work. I could do

data = np.array(zip(a, b, c[0], c[1]))

instead, but the "depth" of
changes. My solution is

data = np.insert(c, 0, b, axis=0)
data = np.insert(data, 0, a, axis=0)
data = zip(*data)

but that reads kind of suboptimal. Thanks for an advice.


I would use numpy.hstack/vstack:

a = np.ones(4) * 5
b = np.ones(4) * 4
c = np.ones((2, 4))
data = np.vstack([a,b,c]).T

Edit: I actually mostly use np.row_stack/column_stack nowadays, as I find it more natural than hstack or vstack:

    data = np.column_stack([a,b,c.T])