Prerequisites: numpy.savetxt(), numpy.loadtxt()
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
Example:
Python3
import numpy as gfg
arr = gfg.random.rand( 5 , 4 , 3 )
arr_reshaped = arr.reshape(arr.shape[ 0 ], - 1 )
gfg.savetxt( "geekfile.txt" , arr_reshaped)
loaded_arr = gfg.loadtxt( "geekfile.txt" )
load_original_arr = loaded_arr.reshape(
loaded_arr.shape[ 0 ], loaded_arr.shape[ 1 ] / / arr.shape[ 2 ], arr.shape[ 2 ])
print ( "shape of arr: " , arr.shape)
print ( "shape of load_original_arr: " , load_original_arr.shape)
if (load_original_arr = = arr). all ():
print ( "Yes, both the arrays are same" )
else :
print ( "No, both the arrays are not same" )
|
Output:
shape of arr: (5, 4, 3)
shape of load_original_arr: (5, 4, 3)
Yes, both the arrays are same
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Sep, 2020
Like Article
Save Article