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.
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.
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.
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.
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 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With