Writing comma separated values โ€‹โ€‹from a numpy python array

I create my own file creator. I need to write the values โ€‹โ€‹of my array as a comma, separated by one line in the file. I could do the following:

def as_csv(array): return ','.join([str(i) for i in array]) + '\n' 

then

 outfile.write(my_header) outfile.write(other_stuff) outfile.write(as_csv(array)) 

but I am wondering if this is the most efficient way to do this, or if there would be a better method using numpy.array_str or numpy.array_repr methods.

+4
source share
2 answers

You can also use the numpy np.savetxt built-in method: http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

 np.savetxt(outfile, array, delimiter=',') 
+6
source

I did not try to use np.savetxt in the context below, maybe it can be used while the file is opening in add mode, but here is the solution for what I was trying to do. However, this may not be the most effective.

 def _as_csv(self, values): vals = ','.join([str(i) for i in values]) return vals + '\n' def output(self, filename, series_cnt, series_name, series_type, startdate, N, values, step = 1000): """ outputs data to a file """ starttime = startdate num_imports = (N / step) + 1 outfile = open(filename.format(series_cnt, i), 'w') outfile.write('#{0},{1},{2},\n'.format('TEST', startdate.strftime('%Y%m%d%H%M%S000'), str(num_imports))) for i in range(0, N, step): line_start = '/Test/{0},{1},{2},{3},'.format(series_name, series_type, starttime.strftime('%Y%m%d%H%M%S000'), step) outfile.write(line_start) nxt = i + step starttime = starttime + dt.timedelta(hours=step) outfile.write(self._as_csv(values[i:nxt])) outfile.close() 
0
source

All Articles