Friday, December 27, 2024
Google search engine
HomeLanguagesHow to load and save 3D Numpy array to file using savetxt()...

How to load and save 3D Numpy array to file using savetxt() and loadtxt() functions?

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)
  
# reshaping the array from 3D
# matrice to 2D matrice.
arr_reshaped = arr.reshape(arr.shape[0], -1)
  
# saving reshaped array to file.
gfg.savetxt("geekfile.txt", arr_reshaped)
  
# retrieving data from file.
loaded_arr = gfg.loadtxt("geekfile.txt")
  
# This loadedArr is a 2D array, therefore
# we need to convert it to the original
# array shape.reshaping to get original
# matrice with original shape.
load_original_arr = loaded_arr.reshape(
    loaded_arr.shape[0], loaded_arr.shape[1] // arr.shape[2], arr.shape[2])
  
# check the shapes:
print("shape of arr: ", arr.shape)
print("shape of load_original_arr: ", load_original_arr.shape)
  
# check if both arrays are same or not:
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
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments