Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using np.savetxt and np.loadtxt with multi-dimensional arrays

What is a generalized way of storing a more-than-2 dimensional array (ndim > 2) to file and retrieving it in same format (dimension) using np.savetxt and np.loadtxt?

My concern is if I give any delimiter while storing, do I need to give some treatments while retrieving? Plus dealing with floats and retrieving it in same format is little tricky.

I have seen many simple examples in the docs. I am just curious about whether the simplest storing np.savetxt(filename, array) can be retrieved using simply array = np.loadtxt(filename) or not.

like image 938
Hima Avatar asked Oct 07 '14 10:10

Hima


People also ask

What does Loadtxt () do in NumPy?

loadtxt() is used to return the n-dimensional NumPy array by reading the data from the text file, with an aim to be a fast reader for simple text files. This function numpy. loadtxt() can be used with both absolute and relative paths. It loads the data from the text file into the NumPy array.

What is the default datatype that NP Loadtxt () uses for numbers?

Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type.

How do you create a two dimensional NumPy array in Python?

In Python to declare a new 2-dimensional array we can easily use the combination of arange and reshape() method. The reshape() method is used to shape a numpy array without updating its data and arange() function is used to create a new array.


1 Answers

If you need to save multi-dimensional arrays in a text file you can use the header parameter to save the original array shape:

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 do:

with open('test.txt') as f:
    shape = map(int, f.next()[1:].split(','))
    b = np.genfromtxt(f, delimiter=',').reshape(shape)
like image 108
Saullo G. P. Castro Avatar answered Oct 19 '22 08:10

Saullo G. P. Castro