2

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.

1
  • 1
    avoid using zip in connection with np.arrays. It will turn them into lists, which is highly undesirable as soon as you start wielding larger datasets. Commented May 30, 2014 at 21:16

3 Answers 3

3

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])
Sign up to request clarification or add additional context in comments.

Comments

2

Use the * opertor to "unpack" c when calling zip:

data = np.array(zip(a, b, *c))
data.shape
=> (4, 4)

(You can avoid zip and use a direct numpy approach (e.g. using vstack, as @metaperture suggested), which is arguably a better approach. However, this answer demostrates the correct way to do exactly what you were trying to do originally)

Comments

2

I would not recommend using zip if your only objective is to save multiple arrays of different dimensions, as the title of this question suggests. Use np.savez or np.savez_compressed instead. These functions were meant to save multiple arrays (of arbitrary dimensions).

Using zip is particularly bad as it won't port to Python3, where zip returns an iterator and not a list of tuples. Calling np.array on the iterator creates an array with a single element of dtype object, which is probably not what you want. I was not able to recover the zipped data after a save and a load.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.