Learn various ways of performing Input/Output (I/O) operations in NumPy.
Generally, NumPy arrays are saved in .npy
or .npz
file format.
The .npy
file is a simple format for saving NumPy arrays to disk with the full information about them. It stores all information about a NumPy array including its dtype and shape so that the array can be reconstructed on any machine despite the machine's architecture. On the other hand, several arrays can be contained into a single file in uncompressed .npz
format.
The numpy.save() function is used to save the array in .npy
format, whereas numpy.savez() is used to save the array in .npz
format.
import numpy as np # Creating two 1-D numpy arrays a = np.arange(start=1, stop=5, step=1) b = np.arange(start=6, stop=10, step=1) # Printing the arrays print("a: ", a) print("b: ", b) print("\n") # Saving the a to .npy format np.save('a.npy', a) # Saving the arrays a and b to .npz format np.savez('ab.npz', a, b)
a: [1 2 3 4] b: [6 7 8 9]
Likewise, the numpy.load() function is used to load the array into the Python code. While loading the .npz file, the individual array can be accessed by passing "arr_0, arr_1, ..... arr_n", a as a key to the loaded object.
# Loading saved data a_loaded = np.load('a.npy') ab_loaded = np.load('ab.npz') # Printing the loaded data print("a_loaded: ", a_loaded) print("First array in ab_loaded: ", ab_loaded['arr_0']) print("Second array in ab_loaded: ", ab_loaded['arr_1'])
a_loaded: [1 2 3 4] First array in the ab_loaded: [1 2 3 4] Second array in the ab_loaded: [6 7 8 9]
NumPy arrays can also be stored in plain .txt
file formats. The numpy.savetxt() and numpy.loadtxt() methods are used to save and load arrays respectively.
import numpy as np # Creating a 1-D numpy arrays a = np.arange(start=1, stop=5, step=1) # Saving array as a txt file np.savetxt("a.txt", a) # Loading array from txt file loaded_arr = np.loadtxt("a.txt") print("Loaded Array: ", loaded_arr)
Loaded Array: [1. 2. 3. 4.]
This is how you can perform Input/Output operations in NumPy!
With this, we have come to the end of our NumPy for Scientific Computing with Python Course. We hope that this course helped you as a stepping stone towards your Data Science journey with Python. If you have any questions or feedback, please feel free to let us know in the comment section.
Also, now that you are able to code in Python, you can enroll in a domain-specific course by going through all of our data science courses.
(As a reminder, we are constantly updating our courses so make sure to check in on a future date to find more resources introduced in this course.)
Do you want to learn Python, Data Science, and Machine Learning while getting certified? Here are some best selling Datacamp courses that we recommend you enroll in: