Numpy.savetxt() is a method in python in numpy library to save an 1D and 2D array to a file.
Syntax: numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=”, footer=”, comments=’# ‘, encoding=None)
numpy.loadtxt() is a method in python in numpy library to load data from a text file for faster reading.
Syntax: numpy.loadtxt(fname, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
Saving and loading 3D arrays
As discussed earlier we can only use 1D or 2D array in numpy.savetxt(), and if we use an array of more dimensions it will throw a ValueError – Expected 1D or 2D array, got 3D array instead. Therefore, we need to find a way to save and retrieve, at least for 3D arrays, here’s how you can do this by using some Python tricks.
- Step 1: reshape the 3D array to 2D array.
- Step 2: Insert this array to the file
- Step 3: Load data from the file to display
- Step 4: convert back to the original shaped array
shape of arr: (5, 4, 3) shape of load_original_arr: (5, 4, 3) Yes, both the arrays are same
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.