How to dump a NumPy array into a CSV file with Python?

Sometimes, we want to dump a NumPy array into a CSV file with Python

In this article, we’ll look at how to dump a NumPy array into a CSV file with Python

How to dump a NumPy array into a CSV file with Python?

To dump a NumPy array into a CSV file with Python, we can use the savetxt method.

For instance, we write:

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

We call numpy.asarray with a nested list to create the a NumPy array.

Then we call savetxt with the path to the file we want to save to, the a array, and the delimiter for the cells.

As a result, in foo.txt, we get:

1.000000000000000000e+00,2.000000000000000000e+00,3.000000000000000000e+00
4.000000000000000000e+00,5.000000000000000000e+00,6.000000000000000000e+00
7.000000000000000000e+00,8.000000000000000000e+00,9.000000000000000000e+00

Conclusion

To dump a NumPy array into a CSV file with Python, we can use the savetxt method.