Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy savetxt formatted as integer is not saving zeroes

I am trying to save numpy.array to .csv in the following way.

with open("resultTR.csv", "wb") as f:     f.write(b'ImageId,Label\n')     numpy.savetxt(f, result, fmt='%i', delimiter=",") 

result is numpy.array that consists of two columns, first column are indices (numbers 1 through n) and second column values from (0,9).

Unfortunately I have problem that whenever there is 0 in the second column then nothing is written to the resulting .csv file in the second column.

In other words first five rows of array looks like this:

[[  1.00000000e+00   2.00000000e+00]  [  2.00000000e+00   0.00000000e+00]  [  3.00000000e+00   9.00000000e+00]  [  4.00000000e+00   9.00000000e+00]  [  5.00000000e+00   3.00000000e+00] 

And first five rows of .csv file like this:

ImageId,Label 1,2 2 3,9 4,9 5,3 

It looks to me like my code should work and thus not saving zeroes seems to me very weird. Does anyone have some idea what can possibly be wrong with my code for writing to .csv file?

EDIT:

Just for compleetnes my python version is 2.7.2 and it's running on Mac OS X 10.9.2

like image 799
ziky90 Avatar asked Mar 21 '14 11:03

ziky90


People also ask

What is FMT in Savetxt?

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='%. 4e', resulting in numbers formatted like ' (%s+%sj)' % (fmt, fmt)

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.

How do I save a NumPy 2D array?

savetxt() is a method in python in numpy library to save an 1D and 2D array to a file. numpy. loadtxt() is a method in python in numpy library to load data from a text file for faster reading.


2 Answers

I would try saving the array as an int array, as in result.astype(int), or in full:

with open("resultTR.csv", "wb") as f:     f.write(b'ImageId,Label\n')     numpy.savetxt(f, result.astype(int), fmt='%i', delimiter=",") 
like image 151
askewchan Avatar answered Oct 10 '22 18:10

askewchan


A cleaner solution is using the argument fmt='%s'.

with open("resultTR.csv", "wb") as f:    f.write(b'ImageId,Label\n')    numpy.savetxt(f, result, fmt='%s', delimiter=",") 
like image 37
Florian Dubost Avatar answered Oct 10 '22 17:10

Florian Dubost