Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format.

share|improve this question
up vote 311 down vote accepted

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=",")
share|improve this answer
1  
is this preferred over looping through the array by dimension? I'm guessing so. – Ehtesh Choudhury May 21 '11 at 10:13
1  
It did. Thanks! – Dexter May 22 '11 at 11:00
17  
you can also change the format of each figure with the fmt keyword. default is '%.18e', this can be hard to read, you can use '%.3e' so only 3 decimals are shown. – Andrea Zonca May 22 '11 at 17:25
1  
Andrea, Yes I used %10.5f. It was pretty convenient. – Dexter May 23 '11 at 9:47
5  
Your method works well for numerical data, but it throws an error for numpy.array of strings. Could you prescribe a method to save as csv for an numpy.array object containing strings? – Ébe Isaac Mar 25 '16 at 14:31

tofile is a convenient function to do this:

import numpy as np
a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
a.tofile('foo.csv',sep=',',format='%10.5f')

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 fuction does not produce multi-line csv files, it saves everything to one line.

share|improve this answer
    
As far as I can tell, this does not produce a csv file, but puts everything on a single line. – Peter Jan 14 '16 at 18:46
    
@Peter, good point, thanks, I've updated the answer. For me it does save ok in csv format (albeit limited to one line). Also, it's clear that the asker's intent is to "dump it in human-readable format" - so I think the answer is relevant and useful. – atomh33ls Jan 15 '16 at 10:35

savetxt may just be sufficient.

share|improve this answer
7  
why don't you give a small example program, please? – Pragyaditya Das Apr 20 '16 at 9:26

If you want to save your numpy array (e.g. your_array = np.array([[1,2],[3,4]])) to one cell, you could convert it first with your_array.tolist().

Then save it the normal way to one cell, with delimiter=';' and the cell in the csv-file will look like this [[1, 2], [2, 4]]

Then you could restore your array like this: your_array = np.array(ast.literal_eval(cell_string))

share|improve this answer

Writing record arrays as CSV files with headers requires a bit more work.

This example reads a CSV file with the header on the first line, then writes the same file.

import numpy as np

# Write an example CSV file with headers on first line
with open('example.csv', 'w') as fp:
    fp.write('''\
col1,col2,col3
1,100.1,string1
2,222.2,second string
''')

# Read it as a Numpy record array
ar = np.recfromcsv('example.csv')
print(repr(ar))
# rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')], 
#           dtype=[('col1', '<i4'), ('col2', '<f8'), ('col3', 'S13')])

# Write as a CSV file with headers on first line
with open('out.csv', 'w') as fp:
    fp.write(','.join(ar.dtype.names) + '\n')
    np.savetxt(fp, ar, '%s', ',')

Note that this example does not consider strings with commas, which would require quotes.

share|improve this answer

It's easy and fast with pandas

import pandas as pd 
df = pd.DataFrame(np_array)
df.to_csv("file_path.csv")
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.