How to use savetxt() and loadtxt() functions to load and save 3D Numpy array files?
How to use the savetxt() and loadtxt() functions to load and save 3D Numpy array files?
In Python, arrays are commonly used with NumPy. Sometimes, data is stored in multidimensional or 3D arrays. If you use the loadtxt() or savetxt() functions to save or load array data, a 2D array is required. If you use a 3D array, you will receive an error like “ValueError: Expected 1D or 2D array, got 3D array instead.”
In this Python and NumPy article, we’ll use two different examples to write code to demonstrate how to save and load arrays using the savetxt() and loadtxt() functions, as well as how to handle 3D arrays. In the first example, a Python program on Google Colab uses the savetxt() and loadtxt() functions to process TXT files. In the other example, these functions will be used with CSV files.
Example 1: Using the savetxt() and loadtxt() Functions to Process TXT Files
Design Steps and Code
-
Step 1 – First, log in with your Gmail account. Go to Google Colab. Open a new Colab notebook and write your Python code.
-
Step 2 – Using numpy arrays, create a 3D array of shape (3, 2, 2).
-
Step 3 – Change the shape of this array to 2D. The array and its shape are also displayed.
-
Step 4 – Use the savetxt function to save the reshaped array to a txt file named myfile.txt.
-
Step 5 – Use the loadtxt function to load the contents of myfile.txt into an array named loaded_myarray, which will have a 2D array shape.
-
Step 6 – Change the shape of loaded_myarray back to 3D. Plot the new array and its shape.
-
Step 7 – Check that all elements of this new array are identical to those of the original array.
Write the following code in a code cell in a Google Colab worksheet.
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)
#Change the array shape to 2D
myarray_reshaped = myarray.reshape(myarray.shape[0], -1)
print("The reshaped 2-d array: ")
print(myarray_reshaped)
#print(myarray_reshaped.base)
#Save the reshaped array using the savetxt function
npp.savetxt("myfile.txt", myarray_reshaped)
#Load the reshaped array data from myfile.txt using the loadtxt function
loaded_myarray = npp.loadtxt("myfile.txt")
print("loaded_myarray shape: ", loaded_myarray.shape)
#Reshape the array to 3D
backtomyarray= loaded_myarray.reshape(myarray.shape[0], myarray.shape[1], myarray.shape[2])
print("backtomyarray shape : ", backtomyarray.shape)
#Check if all elements of the two arrays are the same
if (backtomyarray == myarray).all():
print("All elements are same")
else:
print("All elements are not same")
输出
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
Second example: Using the savetxt and loadtxt functions to save and load (reshape) a 3D array into a CSV file
Design steps and code
-
Step 1 − Sign in with your Google account. Open a new Colab notebook and write your Python code.
-
Step 2 − Import the required library numpy.
-
Step 3 − Using numpy arrays, create a 3D array with a shape of (3, 2, 2). Output the array and its shape.
-
Step 4 − Change the array’s shape to 2D. Output the reshaped array and its shape.
-
Step 5 − Use the savetxt function to save the reshaped array as a CSV file named my_array.csv.
-
Step 6 − Use the loadtxt() function to load the contents of my_array.csv into csvdata, which will have a 2D array shape.
-
Step 7 − Change the shape of csvdata back to 3D. Display the resulting array and output its shape.
-
Step 8 − Verify that all elements of the new array are identical to those of the original array.
Write the following code in the code cell of the Google Colab worksheet
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)
#Change the array shape to 2D
myarray_reshaped = myarray.reshape(myarray.shape[0], myarray.shape[1]*myarray.shape[2])
print("The reshaped 2-d array: ")
print(myarray_reshaped)
# Save the 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)
# Change the array shape back to 3D
backtomyarray = csvdata.reshape(myarray.shape[0], myarray.shape[1], myarray.shape[2])
print("backtomyarray shape : ", backtomyarray.shape)
# Check if the two arrays are the 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 cell 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, two different examples demonstrated how to utilize the savetxt() and loadtxt() functions when working with 3D arrays. The first example used a TXT file, while the second used these functions with a CSV file. Careful programming and syntax are essential for successful execution.