Clemens - 9 months ago 281

Python Question

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

`np.save`

`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`

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