Writing and Reading Large NumPy Arrays
Introduction to NumPy and .npz Files
Welcome to the next step in our journey of handling large datasets. In the last lesson, we explored managing data from compressed JSON files within a zip archive. Today, we will delve into how NumPy, a powerful library for numerical operations, can help us handle large data arrays efficiently by using the .npz file format.
NumPy is widely used in data science and machine learning for its ability to process large arrays and matrices swiftly. The .npz format, specifically, allows us to store multiple NumPy arrays in a single file, making it efficient for storing and accessing large datasets.
Creating Large NumPy Arrays
To begin handling large datasets, we need some large NumPy arrays as examples. Here’s how you can generate large arrays filled with random values using NumPy.
First, let's start by importing the NumPy library. If you're using a personal development environment, you must install it with pip install numpy. On CodeSignal, it's pre-installed.
Next, create two large arrays of random numbers. We’ll use np.random.rand to generate arrays of size 1000x1000. This size is just for demonstration; you can adjust it based on your needs.
Here, array1 and array2 are two-dimensional arrays filled with random floats between 0 and 1, each with a shape of 1000x1000.
Writing Arrays to .npz Files
Now that we have our arrays, let's save them to a .npz file. This file format is efficient, as it can store multiple arrays in a single file.
We use the np.savez function to achieve this:
In this snippet:
np.savezis used to save the arrays into a.npzfile.npz_file_pathis the location where the file will be saved.array1=array1, array2=array2saves each array with a key, so you can retrieve them later.
For saving with compression, which reduces file size at the cost of longer loading time, use np.savez_compressed:
After running this, you should see messages indicating the files have been saved.
