Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy savetxt is not adding comma delimiter

Tags:

python

numpy

numpy savetxt is not adding comma delimiter

I have an array with the following contents:

3.880631596916139792e-01
6.835074831218364011e-01
4.604322858429276133e-01
3.494236368132551673e-01
7.142120448019100287e-01
2.579415438181463793e-01
8.230159985476581674e-01
7.342531681855216652e-01
3.196536650498674748e-01
7.444435819161493439e-01

And I save it as follows:

 np.savetxt('x.train.1.txt',XTraining, delimiter=',') 

However when I look into the txt file, there is no commas.

like image 984
user Avatar asked Feb 06 '17 12:02

user


People also ask

How do I save a 2D NumPy array as a CSV?

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.

What is Savetxt in Python?

savetxt() function in NumPy array Python. In Python, this method is available in the NumPy package module and it saves array numbers in text file format. In this example, we have used the header, delimiter parameter in numpy.

How do I append a NumPy array to a csv file?

The NumPy module savetxt() method is used to append the Numpy array at the end of the existing csv file with a single format pattern fmt = %s. We will open CSV file in append mode and call the savetxt() method to writes rows with header. Second call the savetxt() method to append the rows.

How do I save an array as a text in NP?

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.


1 Answers

I guess the default use case is to store a list of lists, that's why you either need to treat it as list of only one list:

np.savetxt('x.train.1.txt',[XTraining], delimiter=',')

Or put the comma instead of the newlines (note: this adds a trailing comma)

np.savetxt('x.train.1.txt',XTraining, newline=',')
like image 96
hansaplast Avatar answered Sep 25 '22 17:09

hansaplast