NumPy ndarray.dump()
The numpy.ndarray.dump()
method is used to serialize a NumPy array and save it as a binary file in .npy
format.
This method allows saving array data efficiently for later use.
Syntax
ndarray.dump(file)
Parameters
Parameter | Type | Description |
---|---|---|
file | str or file-like object | File path or an open file where the array will be saved in .npy format. |
Return Value
This method does not return any value. It writes the array data directly to the specified file.
Examples
1. Saving a NumPy Array to a File
This example demonstrates how to save a NumPy array to a binary .npy
file using ndarray.dump()
.
import numpy as np
# Create a NumPy array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Specify the file name to save the array
file_name = "array_data.npy"
# Save the array using dump() method
arr.dump(file_name)
print(f"Array successfully saved to {file_name}")
Output:
Array successfully saved to array_data.npy
The array is stored in a binary format in the array_data.npy
file. It can be loaded later using numpy.load()
.
2. Loading a Saved NumPy Array
Once an array is saved using dump()
, it can be reloaded using numpy.load()
.
import numpy as np # Import NumPy library
# Specify the file name where the array was saved
file_name = "array_data.npy"
# Load the saved array
loaded_array = np.load(file_name)
# Print the loaded array
print("Loaded array:")
print(loaded_array)
Output:
Loaded array:
[[1 2 3]
[4 5 6]]
The previously saved array is successfully reloaded and displayed.
3. Saving and Loading a Large NumPy Array
When working with large datasets, ndarray.dump()
efficiently stores arrays in a compressed binary format.
import numpy as np # Import NumPy library
# Create a large NumPy array with random values
large_array = np.random.rand(1000, 1000) # 1000x1000 random float values
# File to save the large array
file_name = "large_array.npy"
# Save the large array
large_array.dump(file_name)
print(f"Large array successfully saved to {file_name}")
# Load the saved large array
loaded_large_array = np.load(file_name)
# Verify the shape of the loaded array
print("Shape of loaded array:", loaded_large_array.shape)
Output:
Large array successfully saved to large_array.npy
Shape of loaded array: (1000, 1000)
The large array is stored and retrieved with the same shape, ensuring data integrity.