
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Saving Arrays
Saving Arrays in NumPy
Saving arrays in NumPy refers to the process of writing NumPy arrays to files so they can be stored and later reloaded.
NumPy provides several methods for saving arrays in various formats, they are −
- np.save() Function: Saves a single NumPy array to a file in binary .npy format.
- np.savez() Function: Saves multiple NumPy arrays into a single file in compressed .npz format.
- np.savez_compressed() Function: Similar to np.savez, but compresses the data for reduced file size.
- np.savetxt() Function: Saves NumPy arrays to a text file with a specific format.
Saving Arrays to Text Files
Saving arrays to text files in NumPy is useful for exporting data in a human-readable format or for compatibility with other programs that require text input.
NumPy uses the np.savetxt() function to write arrays to text files in a specified format. It is designed to handle arrays with numerical data, but it can be adapted for various use cases through formatting options. Following is the syntax −
numpy.savetxt(fname, data, fmt=<format>, delimiter=<delimiter>, header=<header>, footer=<footer>, comments=<char>)
Where,
- fname: Filename or file object where the data will be saved.
- data: The array to be saved. It can be a one-dimensional or multi-dimensional array.
- fmt: Format string for output. Defines how the data should be formatted (e.g., floating-point precision).
- delimiter: String or character separating values in the file (e.g., comma for CSV, space for space-separated).
- header: String to write at the beginning of the file. Useful for adding metadata or column names.
- footer: String to write at the end of the file. Can be used for additional information.
- comments: String indicating the start of a comment. Default is #.
Example
In the following example, we are saving a 2D NumPy array to a text file using np.savetxt() function −
import numpy as np # Create an array array = np.array([[1, 2, 3], [4, 5, 6]]) # Save the array to a text file np.savetxt('data.txt', array, fmt='%d', delimiter=',', header='Column1,Column2,Column3') print ('File Saved succesfully!!')
Following is the output obtained −
File Saved succesfully!!
Saving Arrays to Binary Files
Saving arrays to binary files in NumPy is a way to store numerical data in a compact format. Binary files are often used for saving large datasets or for performance reasons, as they are generally faster to read from and write to compared to text files.
NumPy provides np.save() function, np.savez() function and np.savez_compressed() function specifically designed for saving arrays in binary formats.
Using np.save() Function
The np.save() function saves a single NumPy array to a binary file in NumPys native .npy format. This format includes metadata such as the arrays shape and dtype, which allows for loading and manipulation later. Following is the syntax −
numpy.save(file, arr, allow_pickle=False, fix_imports=True)
Where,
- file: Filename or file object where the array will be saved. The file extension should be .npy.
- arr: The NumPy array to be saved.
- allow_pickle: If True, allows saving objects that can be pickled. Default is False.
- fix_imports: If True, attempts to fix compatibility issues when loading pickled data (for Python 2 to 3).
Example
In this example, we are saving a 2D NumPy array to a binary ".npy" file using np.save() function, which stores the array data efficiently −
import numpy as np # Create an array array = np.array([[1, 2, 3], [4, 5, 6]]) # Save the array to a .npy file np.save('array.npy', array) print ("File saved!!")
This will produce the following result −
File saved!!
Using np.savez() Function
The np.savez() function saves multiple arrays into a single file with the ".npz" extension. The ".npz" file is a zip archive containing one ".npy" file for each array, which can be accessed by name. Following is the syntax −
numpy.savez(file, *args, **kwargs)
Where,
- file: Filename or file object where the arrays will be saved. The file extension should be .npz.
- *args: Arrays to be saved.
- **kwargs: Keyword arguments specifying names for each array.
Example
In the example below, we are saving multiple NumPy arrays to a compressed ".npz" file using np.savez() function, where "array1" and "array2" are stored with their respective names −
import numpy as np # Create multiple arrays array1 = np.array([1, 2, 3]) array2 = np.array([[4, 5, 6], [7, 8, 9]]) # Save the arrays to a .npz file np.savez('arrays.npz', array1=array1, array2=array2) print ("File saved!!")
Following is the output of the above code −
File saved!!
Using np.savez_compressed() Function
The np.savez_compressed() function is similar to np.savez() function, but it compresses the arrays to reduce file size. This is useful for storing large datasets more efficiently. Following is the syntax −
numpy.savez_compressed(file, *args, **kwargs)
Where,
- file: Filename or file object where the arrays will be saved. The file extension should be .npz.
- *args: Arrays to be saved.
- **kwargs: Keyword arguments specifying names for each array.
Example
Here, we save multiple NumPy arrays to a compressed ".npz" file using np.savez_compressed() function, which reduces the file size while storing "array1" and "array2" with their respective names −
import numpy as np # Create multiple arrays array1 = np.array([1, 2, 3]) array2 = np.array([[4, 5, 6], [7, 8, 9]]) # Save the arrays to a compressed .npz file np.savez_compressed('arrays_compressed.npz', array1=array1, array2=array2) print ("File saved!!")
The output obtained is as shown below −
File saved!!