How to save a numpy 2D array in a text file in python ?

Published: June 05, 2023

Tags: Python; Numpy; Protection Status

One of the most common ways to save a 2D NumPy array in a text file is by using the savetxt() function. Example:

Saving a 2D array using savetxt()

This function takes two parameters: an array and a filename. To use this, you simply specify the filename that you would like to save your array into, along with the array itself. You may also specify options such as the delimiter to use, which will determine how the data is organized in the text file. Once you have chosen your desired parameters, simply call savetxt and your array will be saved to a text file. Example

import numpy as np

data = np.arange(1,11)
data = data.reshape(5,2)


The above code generates a file named data.txt, which will include

1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00
5.000000000000000000e+00 6.000000000000000000e+00
7.000000000000000000e+00 8.000000000000000000e+00
9.000000000000000000e+00 1.000000000000000000e+01

Indicating the data format

You can use the "fmt" option to indicate the data format. For instance, if you want to store integers, you can specify it as follows:

np.savetxt('data.txt', data, fmt='%i')

will returns

1 2
3 4
5 6
7 8
9 10

Adding a delimiter

np.savetxt('data.txt', data, fmt='%i', delimiter=';')

will returns


Loading a 2D array using loadtxt()

When loading an array from a text file back into NumPy, you can use the np.loadtxt() function. This takes a single parameter, which is the filename of the text file containing your array data. It will then return the array as a NumPy object that you can further manipulate and analyze, just like any other NumPy array.

new_data = np.loadtxt('data.txt')


will return

array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.],
       [ 7.,  8.],
       [ 9., 10.]])

Loadtxt with a delimiter

new_data = np.loadtxt('data.txt', delimiter=';')

will return

array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.],
       [ 7.,  8.],
       [ 9., 10.]])

By using these two functions together, you can easily save and load 2D NumPy arrays in text files, allowing you to store data for later use or share it with others.


Links Site