Home » How to Export a NumPy Array to a CSV File (With Examples)

How to Export a NumPy Array to a CSV File (With Examples)

by Tutor Aspire

You can use the following basic syntax to export a NumPy array to a CSV file:

import numpy as np

#define NumPy array
data = np.array([[1,2,3],[4,5,6],[7,8,9]])

#export array to CSV file
np.savetxt("my_data.csv", data, delimiter=",")

The following examples show how to use this syntax in practice.

Example 1: Export NumPy Array to CSV

The following code shows how to export a NumPy array to a CSV file:

import numpy as np

#define NumPy array
data = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12], [13, 14, 15]])

#export array to CSV file
np.savetxt("my_data.csv", data, delimiter=",")

If I navigate to the location where the CSV file is saved on my laptop, I can view the data:

Example 2: Export NumPy Array to CSV With Specific Format

The default format for numbers is “%.18e” – this displays 18 zeros. However, we can use the fmt argument to specify a different format.

For example, the following code exports a NumPy array to CSV and specifies two decimal places:

import numpy as np

#define NumPy array
data = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12], [13, 14, 15]])

#export array to CSV file (using 2 decimal places)
np.savetxt("my_data.csv", data, delimiter=",", fmt="%.2f")

If I navigate to the location where the CSV file is saved, I can view the data:

Example 3: Export NumPy Array to CSV With Headers

The following code shows how to export a NumPy array to a CSV file with custom column headers:

import numpy as np

#define NumPy array
data = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12], [13, 14, 15]])

#export array to CSV file (using 2 decimal places)
np.savetxt("my_data.csv", data, delimiter=",", fmt="%.2f",
           header="A, B, C", comments="")

Note: The comments argument prevents a “#” symbol from being displayed in the headers.

If I navigate to the location where the CSV file is saved, I can view the data:

Note: You can find the complete documentation for the numpy.savetxt() function here.

Additional Resources

The following tutorials explain how to perform other common read and write operations in Python:

How to Read CSV Files with NumPy
How to Read CSV Files with Pandas
How to Export Pandas DataFrame to CSV File

You may also like