Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 05 Sep, 2020

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!