Saving and Loading Arrays
NumPy allows us to save and retrieve arrays efficiently in binary or text format.
a) Saving and Loading a NumPy Array (Binary Format)
# Create an array a = np.array([1, 2, 3, 4, 5]) # Save array to a binary file np.save('data.npy', a) # Load the array from the file b = np.load('data.npy') print("Loaded Array:", b)
Why Use .npy Format?
- Stores data in a compact binary format.
- Faster loading and saving compared to CSV or text files.
- Retains data type and structure of arrays.
b) Saving and Loading Multiple Arrays
We can save multiple arrays in a single file using np.savez().
# Create multiple arrays arr1 = np.array([1, 2, 3]) arr2 = np.array([10, 20, 30]) # Save both arrays in a single file np.savez('multi_data.npz', array1=arr1, array2=arr2) # Load the arrays from file loaded_data = np.load('multi_data.npz') print("Array 1:", loaded_data['array1']) print("Array 2:", loaded_data['array2'])
When to Use .npz Format?
- When working with large datasets where multiple arrays need to be stored efficiently.
- Reduces disk space usage while maintaining fast I/O speeds.
c) Saving and Loading CSV Files
Many real-world datasets are stored in CSV format. NumPy makes it easy to save and load CSV files.
Saving a NumPy Array as a CSV File
# Create a sample array data = np.array([[1, 2, 3], [4, 5, 6]]) # Save to CSV np.savetxt('data.csv', data, delimiter=',')
Loading Data from a CSV File
# Load CSV file loaded_data = np.loadtxt('data.csv', delimiter=',') print("Loaded CSV Data:\n", loaded_data)
Use Case:
- CSV files are widely used in data science, machine learning, and finance.