Input/Output operations in NumPy
November 24, 2020 2020-12-03 21:18Input/Output operations in NumPy
NumPy provides built-in functions for efficiently saving NumPy arrays as external files in the disk and also for loading the NumPy array from a file into your Python code. In this chapter, you will learn various ways of performing I/O operations in NumPy.
NPY and NPZ files in NumPy
Generally, the arrays are saved in files with the format .npy
and .npz
. The .npy
files store all the information required to reconstruct an array on any computer, which includes dtype and shape information whereas, several arrays are 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. 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.
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) # 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 the ab_loaded: ", ab_loaded['arr_0']) print("Second array in the ab_loaded: ", ab_loaded['arr_1'])
a: [1 2 3 4] b: [6 7 8 9] 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]
TXT Files in NumPy
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!
End of Course
With this, we have come to the end of our NumPy for Data Science 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 intermediate and expert 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.)