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.
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])
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 (eg 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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.