- NumPy | savetxt method
- Parameters
- Return value
- Examples
- Basic usage
- numpy.savetxt#
- np.savetxt: как сохранить массив в текстовый файл в Python
- np.savext
- Синтаксис
- Параметры
- Пример
- Numpy Savetxt: How to save Numpy Array to text and CSV File
- How to Save One Dimensional Numpy array using numpy.savetxt()
- Save Two Dimensional Numpy array using numpy.savetxt()
- How to Save a Structured Numpy array in CSV file?
- Save more than one NumPy array
- Conclusion
- Join our list
NumPy | savetxt method
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
Numpy’s savetxt(~) method saves a Numpy array as a text file.
Parameters
The name of the file. If the file is not in the same directory as the script, make sure to include the path to the file as well.
A 1D or 2D array that you wish to save.
3. fmt | string or sequence | optional
The format in which to save the data. The syntax follows that of Python’s standard string formatter:
By default, fmt=»%.18e» , which means to store each value as a float (this is implicit) with 18 precision (i.e. up to 18 decimal places will be shown).
The formats in the table are not exhaustive
Consult Python’s official documentation to find out the details.
The string used to separate your data. By default, the delimiter is a single whitespace.
The string used to denote a new line. By default, for 1D arrays, each value is stored in a separate line, and for 2D arrays, each row is stored in a separate line.
The string written at the very first line of the file. By default, no header will be written.
The string written at the very bottom of the file. By default, no footer will be written.
8. comments link | string or list | optional
The string to prepend to the header and footer if they are specified. The intention is to mark them as comments. By default, comments=»#» .
9. encoding | string | optional
The encoding to use when writing the file (e.g. «latin-1», «iso-8859-1″). By default, encoding=»bytes».
Return value
Examples
Basic usage
To save a 1D Numpy array of integers:
numpy.savetxt#
If the filename ends in .gz , the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently.
X 1D or 2D array_like
Data to be saved to a text file.
fmt str or sequence of strs, optional
A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case delimiter is ignored. For complex X, the legal options for fmt are:
- a single specifier, fmt=’%.4e’, resulting in numbers formatted like ‘ (%s+%sj)’ % (fmt, fmt)
- a full string specifying every real and imaginary part, e.g. ‘ %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej’ for 3 columns
- a list of specifiers, one per column — in this case, the real and imaginary part must have separate specifiers, e.g. [‘%.3e + %.3ej’, ‘(%.15e%+.15ej)’] for 2 columns
String or character separating columns.
newline str, optional
String or character separating lines.
String that will be written at the beginning of the file.
String that will be written at the end of the file.
String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt .
Encoding used to encode the outputfile. Does not apply to output streams. If the encoding is something other than ‘bytes’ or ‘latin1’ you will not be able to load the file in NumPy versions < 1.14. Default is ‘latin1’.
Save an array to a binary file in NumPy .npy format
Save several arrays into an uncompressed .npz archive
Save several arrays into a compressed .npz archive
Further explanation of the fmt parameter ( %[flag]width[.precision]specifier ):
+ : Forces to precede result with + or -.
0 : Left pad the number with zeros instead of space (see width).
Minimum number of characters to be printed. The value is not truncated if it has more characters.
- For integer specifiers (eg. d,i,o,x ), the minimum number of digits.
- For e, E and f specifiers, the number of digits to print after the decimal point.
- For g and G , the maximum number of significant digits.
- For s , the maximum number of characters.
d or i : signed decimal integer
e or E : scientific notation with e or E .
f : decimal floating point
g,G : use the shorter of e,E or f
u : unsigned decimal integer
x,X : unsigned hexadecimal integer
This explanation of fmt is not complete, for an exhaustive specification see [1].
>>> x = y = z = np.arange(0.0,5.0,1.0) >>> np.savetxt('test.out', x, delimiter=',') # X is an array >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation
np.savetxt: как сохранить массив в текстовый файл в Python
Массивы Numpy — это эффективные структуры данных для работы с данными в Python, а модели машинного обучения в библиотеке scikit-learn и модели глубокого обучения в библиотеке Tensorflow и Keras ожидают входные данные в формате массивов Numpy и делают прогнозы в формате массивов Numpy.
np.savext
Функция np.savetxt() принимает два обязательных параметра: file name и data, сохраняет и загружает массив в текстовый файл в Python. Чтобы сохранить массив numpy в текстовый файл, используйте метод numpy savetxt().
Функция numpy.savetxt() помогает пользователю сохранить массив numpy в текстовый файл вместе с тем, что мы использовали параметр формата в функции.
Синтаксис
Параметры
Если имя файла заканчивается на .gz, файл автоматически сохраняется в сжатом формате gzip. Функция loadtxt() прозрачно понимает сжатые gzip-файлы.
[1D или 2D array_like] Данные для сохранения в текстовый файл.Одиночный формат(%10.5f), последовательность форматов или многоформатная строка, например, «Итерация %d — %10.5f», в этом случае разделитель игнорируется.
Строка или символ, разделяющий столбцы.
Строка или символ, разделяющий строки.
Строка будет записана в начало файла.
Строка будет записана в конец файла.
Строка, которая будет добавлена к строкам заголовка и нижнего колонтитула, чтобы пометить их как комментарии. По умолчанию: ‘#’, как и ожидалось, например, для функции numpy.loadtxt().
Кодировка используется для кодирования выходного файла. Это не относится к выходным потокам. Если кодировка отличается от «bytes» или «latin1», вы не сможете загрузить файл в версиях NumPy < 1.14. По умолчанию используется «latin1».
Пример
В этом примере мы создаем массив с помощью функции np arange(), а затем сохраняем этот массив в текстовом файле с помощью функции savetxt(). См. следующий код.
Numpy Savetxt: How to save Numpy Array to text and CSV File
Numpy Savetxt is a method to save an array to a text file or CSV file. In this coding tutorial, I will show you the implementation of the NumPy savetxt() method using the best examples I have compiled.
First of all, let’s import all the necessary libraries required for this tutorial. Here I am using only NumPy library.
How to Save One Dimensional Numpy array using numpy.savetxt()
In this section, I will create a one-dimensional NumPy array. Then after saving it to both as a text file and CSV file.
Saving to text file
Here I am passing the filename, the array I want to save and delimiter to split the array elements after the comma.
Saving to a CSV File
You can save it to a CSV file by just changing the name of the file.
There is something you should be careful about. You have to pass your 1D Numpy array inside the square bracket. And fmt=”%d” as by default the array will be stored as float type. Here We are using the values of integer type.
You can also add a header and footer argument inside the np.savetxt() method. Just execute the following code.
Output
Save Two Dimensional Numpy array using numpy.savetxt()
The above example was for one dimensional array. Now let’s save the two-dimensional array as a text and CSV file. Let’s create a Two Dimensional Array.
Saving to a text file
Output
Saving to a CSV File
Output
You can also see how I am not the square bracket for array_2d as here it is not required.
How to Save a Structured Numpy array in CSV file?
You can also save a Structured Numpy array to a CSV file. Those Numpy arrays that has a custom data type (dtype) is a structured Numpy array. Below is the code for the Structured Numpy array.
Here I am defining the name, roll no, and marks with their corresponding type.
Now you can save the strud_array with the header as Name, RollNo, and Marks. It will act as the column name in your CSV File.
Save more than one NumPy array
In this section, I will show you how you can save more than one Numpy array to both text file and CSV file.
Let’s create three Numpy array.
Save to text file
Saving to CSV File
Here In both cases, I am passing the set of Numpy array. All arrays will be appended to the next row of the file.
Conclusion
Numpy savetxt method is very useful for saving and retrieving your own dataset. You can manipulate or change any existing dataset and save it. These are examples I have coded for getting a deep understanding. If you have any queries then you can contact us for more information.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.