Thanks to theidioms.com

Learn NumPy for Data Science (Course II)

Learn NumPy for Data Science (Course II)

Input-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!

Leave your thought here

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami