Using np.savetxt and np.loadtxt with multidimensional arrays

What is a generalized way to store an array of more than 2-dimensional size ( ndim > 2 ) for a file and get it in the same format (dimension) using np.savetxt and np.loadtxt ?

My concern is that I give some sort of separator during storage, do I need to give some processing during extraction? Plus, dealing with floats and retrieving it in the same format is a bit difficult.

I saw many simple examples in the docs. I'm just wondering if you can get the simplest save np.savetxt(filename, array) with just array = np.loadtxt(filename) or not.

+5
source share
1 answer

If you need to save multidimensional arrays in a text file, you can use the header parameter to save the original form of the array:

 import numpy as np a = np.random.random((2, 3, 4, 5)) header = ','.join(map(str, a.shape)) np.savetxt('test.txt', a.reshape(-1, a.shape[-1]), header=header, delimiter=',') 

And to load this array you can:

 with open('test.txt') as f: shape = map(int, f.next()[1:].split(',')) b = np.genfromtxt(f, delimiter=',').reshape(shape) 
+3
source

Source: https://habr.com/ru/post/1204164/


All Articles