Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump a NumPy array into a csv file

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.

like image 504
Dexter Avatar asked May 21 '11 10:05

Dexter


People also ask

How do I pass an array into a csv file?

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.

How do I save a NumPy array in Excel?

Use “savetxt” method of numpy to save numpy array to csv file. CSV files are easy to share and view, therefore it's useful to convert numpy array to csv. CSV stands for comma separated values and these can be viewed in excel or any text editor whereas to view a numpy array object we need python.

How do I save a NumPy array to a text file?

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.


2 Answers

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=",") 
like image 185
Jim Brissom Avatar answered Sep 23 '22 21:09

Jim Brissom


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

import pandas as pd  pd.DataFrame(np_array).to_csv("path/to/file.csv") 

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

like image 26
maxbellec Avatar answered Sep 24 '22 21:09

maxbellec