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


For using arrays in Python, NumPy is commonly used. Sometimes, the data is stored in a multidimensional or 3D array. If loadtxt() or savetxt() functions are used to save or load the array data, it will require a 2d array. If the 3D array is used, then it will give this error – “ValueError: Expected 1D or 2D array, got 3D array instead”.

So, in this Python and Numpy article, using two different examples, code is written to show the process of saving arrays and loading arrays while using savetxt() and loadtxt() functions and working with 3D arrays. In the first example, the Python program on Google Colab uses the savetxt() and loadtxt() functions for TXT files. In another example, these functions would be used for CSV files.

Example 1: Utilize the savetxt() and loadtxt() functions for TXT files

Design Steps and Coding

  • Step 1 − First login using gmail account. Go to Google Colab. Open a new Colab Notebook and write the Python code in it.

  • Step 2 − Using numpy array, creation of a 3D array of shape(3,2,2).

  • Step 3 − Change the shape of this array to 2D. Showcase the array and its shape also.

  • Step 4 − Save the reshaped array to a txt file called myfile.txt using the savetxt function.

  • Step 5 − Load the contents of myfile.txt using the loadtxt function into an array called loaded_myarray which will have a 2D array shape.

  • Step 6 − Change the shape of this loaded_myarray back to 3D. Print the new array and print its shape.

  • Step 7 − Check that all elements of this new array and the original array are the same.

Write the following code in the Google Colab Worksheet’s code cell

import numpy as npp
from numpy import newaxis
myarray = npp.array([[[3,18], [46, 79]], [[89, 91], [66, 75]],[[77,34],[21,19]]])
print("The 3-d array: ",myarray)
print("Myarray shape: ", myarray.shape)
  
#Changing the array shape to 2D
myarray_reshaped = myarray.reshape(myarray.shape[0], -1)
print("The rehaped 2-d array: ")
print(myarray_reshaped)
#print(myarray_reshaped.base)
  
# saving this reshaped array to myfile.txt
npp.savetxt("myfile.txt", myarray_reshaped)
  
# loading the reshaped array data from myfile.txt
loaded_myarray = npp.loadtxt("myfile.txt")
print("loaded_myarray shape: ", loaded_myarray.shape)
  
#Changing the array shape back to 3D
backtomyarray= loaded_myarray.reshape(myarray.shape[0], myarray.shape[1], myarray.shape[2])
print("backtomyarray shape : ", backtomyarray.shape)
  
# checking if both the Arrays are same
if (backtomyarray == myarray).all():
    print("All elements are same")
else:
    print("All elements are not same")

Output

The 3-d array:  [[[ 3 18]
  [46 79]]

 [[89 91]
  [66 75]]

 [[77 34]
  [21 19]]]
Myarray shape:  (3, 2, 2)
The rehaped 2-d array: 
[[ 3 18 46 79]
 [89 91 66 75]
 [77 34 21 19]]
loaded_myarray shape:  (3, 4)
backtomyarray shape :  (3, 2, 2)
All elements are same

Example 2: Saving and loading the 3D arrays(reshaped) into CSV files by using savetxt and loadtxt functions respectively

Design Steps and Coding

  • Step 1 − Login using Google account. Open a new Colab Notebook and write the python code in it.

  • Step 2 − Import the required library numpy.

  • Step 3 − Using numpy array, develop a 3D array of shape (3,2,2). Print it and print its shape.

  • Step 4 − Change the shape of this array to 2D. Print the reshaped array and print its shape.

  • Step 5 − Save the reshaped array to a CSV file called my_array.csv using the savetxt function.

  • Step 6 − Utilize the loadtxt() function to load the contents of my_array.csv into csvdata which will have a 2D array shape.

  • Step 7 − Alter the shape of this csvdata back to 3D. Display the resultant array and print its shape.

  • Step 8 − Verify that all elements of this new array and the original array would be same.

Write the following code in the Google Colab Worksheet’s code cell

import numpy as npp
myarray = npp.array([[[3,18], [46, 79]], [[89, 91], [66, 75]],[[77,34],[21,19]]])
print("The 3-d array: ",myarray)
print("Myarray shape: ", myarray.shape)

#Changing the array shape to 2D
myarray_reshaped = myarray.reshape(myarray.shape[0], myarray.shape[1]*myarray.shape[2])
print("The rehaped 2-d array: ")
print(myarray_reshaped)
# saving this reshaped array to my_array.csv
npp.savetxt("my_array.csv", myarray_reshaped, delimiter=",", fmt="%d")
mycsv = open("my_array.csv", 'r')
print("the mycsv file contains:")
print(mycsv.read())

csvdata = npp.loadtxt('my_data.csv', delimiter=',').astype(int)
print(csvdata)
#Changing the array shape back to 3D
backtomyarray= csvdata.reshape(myarray.shape[0], myarray.shape[1], myarray.shape[2])
print("backtomyarray shape : ", backtomyarray.shape)
  
# checking if both the Arrays are same
if (backtomyarray == myarray).all():
    print("All elements are same")
else:
    print("All elements are not same")

Output

Press the play button on the code cells to see the results

The 3-d array:  [[[ 3 18]
  [46 79]]

 [[89 91]
  [66 75]]

 [[77 34]
  [21 19]]]
Myarray shape:  (3, 2, 2)
The rehaped 2-d array: 
[[ 3 18 46 79]
 [89 91 66 75]
 [77 34 21 19]]
the mycsv file contains:
3,18,46,79
89,91,66,75
77,34,21,19

Conclusion

In this Python and Numpy article, by two different examples, the ways to show how to utilize savetxt() and loadtxt() functions while using the 3D arrays are given. First, the method is given where savetxt() and loadtxt() functions are used with TXT files whereas CSV files are used in the second example along with these functions. The program code and syntax should be written carefully to execute the program.

Updated on: 11-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements