Learn NumPy · 14/15

File I/O: Saving and Loading Data 💾

6 min read

So you've done all this amazing work with NumPy, creating arrays, performing complex calculations, and now... what? Does all that hard work just vanish into thin air once you close your program? Not on our watch! Welcome to the essential guide on saving and loading your data.

Think of it like this: you've just cooked an elaborate multi-course meal (your NumPy array). You wouldn't want to throw out the leftovers, right? You'd store them in containers to enjoy later. That's precisely what we're going to do with our arrays. We'll learn how to pack them up, save them to files, and then bring them back to life whenever we need them.

Exporting Data: Saving Arrays to Text Files with np.savetxt()

First up, let's talk about saving our data in a format that even a non-programmer can understand: a plain old text file. This is super handy for creating files like CSVs (Comma-Separated Values) that you can open in spreadsheet software like Excel or Google Sheets.

The problem is, how do you translate the structured data of a NumPy array into a simple text file? The solution is np.savetxt().

This function takes your array and writes it to a text file. You get to decide what the file is called and, most importantly, how the values in your array are separated. This "separator" is called a delimiter.

A Simple Example

Let's say we have an array of student grades, and we want to save it to a file called grades.csv.

python
import numpy as np

# Our array of student grades
grades = np.array([[85, 92, 78], [95, 88, 91], [76, 85, 80]])

# Save it to a CSV file
np.savetxt('grades.csv', grades, delimiter=',')

And just like that, you have a file named grades.csv in the same directory as your script. If you open it, it will look like this:

apache
8.500000000000000000e+01,9.200000000000000000e+01,7.800000000000000000e+01
9.500000000000000000e+01,8.800000000000000000e+01,9.100000000000000000e+01
7.600000000000000000e+01,8.500000000000000000e+01,8.000000000000000000e+01

Whoa, what's with all the weird numbers? That's scientific notation, the default format. We can make it more readable by specifying the format.

python
np.savetxt('grades.csv', grades, delimiter=',', fmt='%d')

Now our grades.csv looks much cleaner:

apache
85,92,78
95,88,91
76,85,80

Interesting Fact: The concept of saving data to text files has been around since the early days of computing. It's a simple and robust way to ensure data can be read by a wide variety of programs, even decades later!

Importing Data: Loading CSVs with np.genfromtxt()

Great, we've saved our data. But what about getting it back into a NumPy array? This is where np.genfromtxt() comes to the rescue.

The problem: How do we read a text file, like our grades.csv, and reconstruct it into a NumPy array? np.genfromtxt() is designed for this. It's smart enough to handle various delimiters and can even deal with missing data, a common headache in the real world.

Loading Our Saved Data

Let's load the grades.csv file we just created.

python
import numpy as np

# Load the data from the CSV file
loaded_grades = np.genfromtxt('grades.csv', delimiter=',')

print(loaded_grades)

The output will be our original NumPy array!

lua
[[85. 92. 78.]
 [95. 88. 91.]
 [76. 85. 80.]]

Notice that the numbers are now floating-point numbers (they have a decimal). This is the default behavior of np.genfromtxt(). You can specify the data type if you need integers.

Handling Missing Data

Imagine our grades.csv file has a missing value:

apache
85,92,78
95,,91
76,85,80

If we try to load this with our previous code, we'll get a nan (Not a Number) value where the data is missing. np.genfromtxt() is clever enough to not crash and to flag the missing data for us.

Saving to Native NumPy Formats: .npy and .npz

Text files are great for readability, but they're not always the most efficient way to store data, especially for large arrays. They can be slow to read and write, and they don't preserve the exact data types of your array elements.

The problem: How can we save our NumPy arrays in a way that's fast, space-efficient, and preserves all the important information about our array? NumPy has its own binary file formats for this: .npy and .npz.

Think of .npy and .npz as NumPy's specialized, high-performance storage containers.

.npy for a Single Array

If you have a single array to save, np.save() is your function. It will save your array to a binary file with a .npy extension.

python
import numpy as np

my_array = np.arange(10)

np.save('my_single_array.npy', my_array)

You won't be able to open this file in a text editor and make sense of it, but trust us, NumPy knows exactly what to do with it.

.npz for Multiple Arrays

What if you have several arrays you want to save together? That's where np.savez() comes in handy. It saves multiple arrays into a single, uncompressed .npz file.

python
import numpy as np

array_one = np.array([1, 2, 3])
array_two = np.array([[4, 5, 6], [7, 8, 9]])

np.savez('my_multiple_arrays.npz', first=array_one, second=array_two)

Here, we're saving two arrays and giving them names ('first' and 'second') so we can easily identify them later. If you don't provide names, NumPy will name them arr_0, arr_1, and so on.

Funny Exaggeration: Trying to read a .npy file with a regular text editor is like trying to read an ancient alien language. You'll see a lot of strange symbols, and you might accidentally summon a friendly but confused space octopus. Best to let NumPy handle the translation.

Loading Native Formats: Efficiently Restoring Data with np.load()

Now that we have our data neatly packed away in .npy and .npz files, how do we get it back? With the versatile np.load() function.

This single function can handle both .npy and .npz files, making it your one-stop shop for loading NumPy's native formats.

Loading a .npy File

Loading a single array from a .npy file is as simple as saving it.

python
import numpy as np

loaded_array = np.load('my_single_array.npy')

print(loaded_array)

Loading a .npz File

When you load a .npz file, you get a special NpzFile object. You can think of this object as being similar to a Python dictionary, where the keys are the names you gave your arrays when you saved them.

python
import numpy as np

data = np.load('my_multiple_arrays.npz')

print(data.files) # See the names of the arrays in the file

array_one_back = data['first']
array_two_back = data['second']

print(array_one_back)
print(array_two_back)

And there you have it! You've successfully saved and loaded your NumPy arrays using both human-readable text files and efficient binary formats. Now your data can live on, ready for your next coding adventure!

References for Further Reading:

Challenge

You are working with data from a scientific experiment. You have two NumPy arrays: sensor_readings containing integer measurements, and timestamps containing floating-point time values. Your task is to write the Python code to perform several data persistence operations using NumPy.

You are given the following initial arrays:

python
import numpy as np

sensor_readings = np.array([[10, 12, 15], [11, 14, 16], [9, 10, 13]])
timestamps = np.array([1672531200.5, 1672531201.7, 1672531202.9])

Your script should accomplish the following, in order:

  1. Save the sensor_readings array to a text file named 'readings.csv'. The values should be comma-delimited integers.
  2. Save both the sensor_readings and timestamps arrays into a single, uncompressed binary file named 'experiment_data.npz'. Inside this file, name the sensor data 'readings' and the timestamp data 'times'.
  3. Write the code to load the data from 'readings.csv' into a new variable named loaded_readings.
  4. Write the code to load the 'experiment_data.npz' file. From the loaded data, extract the sensor readings into a variable named loaded_sensor_data and the timestamps into a variable named loaded_timestamp_data.

Expected result

Your final code should correctly use NumPy functions to save and load data as specified. The solution should look similar to this:

python
import numpy as np

# Initial data
sensor_readings = np.array([[10, 12, 15], [11, 14, 16], [9, 10, 13]])
timestamps = np.array([1672531200.5, 1672531201.7, 1672531202.9])

# 1. Save sensor_readings to 'readings.csv'
np.savetxt('readings.csv', sensor_readings, fmt='%d', delimiter=',')

# 2. Save both arrays to 'experiment_data.npz'
np.savez('experiment_data.npz', readings=sensor_readings, times=timestamps)

# 3. Load data from 'readings.csv'
loaded_readings = np.genfromtxt('readings.csv', delimiter=',')

# 4. Load data from 'experiment_data.npz' and extract arrays
data_archive = np.load('experiment_data.npz')
loaded_sensor_data = data_archive['readings']
loaded_timestamp_data = data_archive['times']
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.