Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy savetxt to a string

Tags:

python

numpy

I would like to load the result of numpy.savetxt into a string. Essentially the following code without the intermediate file:

import numpy as np

def savetxts(arr):
    np.savetxt('tmp', arr)
    with open('tmp', 'rb') as f:
        return f.read()
like image 766
CookieOfFortune Avatar asked Mar 12 '14 14:03

CookieOfFortune


People also ask

How to save an array to a text file in NumPy?

numpy.savetxt (fname, X, fmt='%.18e', delimiter=' ', newline=' ', header='', footer='', comments='# ', encoding=None) : This method is used to save an array to a text file. fname : If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently.

What is the use of NumPy savetxt?

Mainly NumPy savetxt function is used to save arrays in txt format with different delimiters. NumPy savetxt function works with 1D and 2D arrays, the numpy savetxt also saves array elements in csv file format. Arrays play a major role in data science where speed matters.

How to use the header parameter in NumPy savetxt?

Here we can use the header parameter in numpy.savetxt () function. This parameter indicates the input string can be written at the starting of the file. In this example, we have given the header value= “Integer values”. Once you will print ‘final_result’ then the output will display the values in the text file along with the header name.

How to format data in savetxt?

You have to specify the format ( fmt) of you data in savetxt, in this case as a string ( %s ): The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message. And what happens if I want to format the numbers? How can I give some format to the numbers only?


Video Answer


1 Answers

For Python 3.x you can use the io module:

>>> import io
>>> s = io.BytesIO()
>>> np.savetxt(s, (1, 2, 3), '%.4f')
>>> s.getvalue()
b'1.0000\n2.0000\n3.0000\n'

>>> s.getvalue().decode()
'1.0000\n2.0000\n3.0000\n'

Note: I couldn't get io.StringIO() to work. Any ideas?

like image 116
Tom Pohl Avatar answered Nov 02 '22 22:11

Tom Pohl