Clemens Clemens - 4 months ago 157
Python Question

Python zip numpy arrays of different dimension

I'd like to zip numpy arrays befor saving it via

np.save
. 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))


but

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
c
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.

Answer

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])