From a loop I'm getting an array. I want to save this arrays in a tempfile
.
The problem is that np.savez
only saves the last array from the loop. I think I understand why this happens, but dont know how to do it better.
To solve my problem I had the idea to open the tempfile in mode=a+b
with the goal to append the new arrays from the loop. But this doesn't work.
My code so far:
tmp = TemporaryFile(mode="a+b")
for i in range(10):
array = getarray[i] #demo purpose
np.savez(tmp,array)
tmp.seek(0)
Then using the tempfile to read the arrays:
tmp_read = np.load(tmp)
print tmp_read.files
[OUTPUT]: ['arr_0']
But I want 10 arrays in the tempfile. Any ideas?
thanks
Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.
npz overwrites everything but the purpose of the loop is to 'append' the next array, this won't work.
Save several arrays into a single file in uncompressed . npz format. Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y) .
Can an array store different data types? Yes, a numpy array can store different data String, Integer, Complex, Float, Boolean.
The savez_compressed () NumPy function allows multiple NumPy arrays to be saved to a single compressed.npz file. 3.1 Example of Saving a NumPy Array to NPZ File We can use this function to save our single NumPy array to a compressed file. The complete example is listed below.
The .npz file format is appropriate for this case and supports a compressed version of the native NumPy file format. The savez_compressed () NumPy function allows multiple NumPy arrays to be saved to a single compressed .npz file. We can use this function to save our single NumPy array to a compressed file.
numpy.save () function is used to store the input array in a disk file with npy extension (.npy). Syntax : numpy.save (file, arr, allow_pickle=True, fix_imports=True)
The savez () function is used to save several arrays into a single file in uncompressed .npz format. If keyword arguments are given, the corresponding variable names, in the .npz file will match the keyword names. Version: 1.15.0 Either the file name (string) or an open file (file-like object) where the data will be saved.
You can use the *args
arguments to save many arrays in only one temp file.
np.savez(tmp, *getarray[:10])
or:
np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With