python – Dump a NumPy array into a csv file

python – Dump a NumPy array into a csv file

numpy.savetxt saves an array to a text file.

import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt(foo.csv, a, delimiter=,)

You can use pandas. It does take some extra memory so its not always possible, but its very fast and easy to use.

import pandas as pd 

if you dont want a header or index, use to_csv(/path/to/file.csv, header=None, index=None)

python – Dump a NumPy array into a csv file

tofile is a convenient function to do this:

import numpy as np
a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])

The man page has some useful notes:

This is a convenience function for quick storage of array data.
Information on endianness and precision is lost, so this method is not
a good choice for files intended to archive data or transport data
between machines with different endianness. Some of these problems can
be overcome by outputting the data as text files, at the expense of
speed and file size.

Note. This function does not produce multi-line csv files, it saves everything to one line.

Leave a Reply

Your email address will not be published. Required fields are marked *