I am using the following to save the numpy array x with a header:
np.savetxt("foo.csv", x, delimiter=",", header="ID,AMOUNT", fmt="%i")
However, if I open "foo.cv", the file looks like:
# ID,AMOUNT
21,100
52,120
63,29
:
There is an extra #
character in the beginning of the header. Why is that and is there a way to get rid of it?
The savetxt() function is used to save an array to a text file. Syntax: numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='#', encoding=None) Version: 1.15.0. Parameter: Name.
Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.
Data to be saved to a text file. fmtstr 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='%.
You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.
The header and footer text are added as comments. If you want to change the comment identifier, pass the comments
option (the default is #
):
np.savetxt("foo.csv", x, delimiter=",", header="ID,AMOUNT",
fmt="%i", comments='')
As documented here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With