HOWTO · NumPy
How to Write NumPy Array to CSV in Python
This tutorial demonstrates how to save a NumPy array in a CSV file using Python. Learn different methods, including NumPy's `savetxt`, Pandas DataFrame, and the CSV module. Follow along with clear examples and explanations to master exporting data efficiently.
On this page
Use numpy.savetxt() to write a numeric NumPy array as comma-delimited text. Choose pandas when the array belongs in a DataFrame workflow, or csv.writer when you need to build or customize rows. CSV stores rows and columns, so decide how a one-dimensional or higher-dimensional array should map to those rows before saving it.
The examples use a small two-dimensional array with integer values. Each writes just the values, without a header or index. NumPy is required for the array examples; pandas is an additional package and is only needed for its section.
Choose a method based on the array and output you need
For a numeric array and a simple delimited text file, numpy.savetxt() is a direct default. Its delimiter controls the separator and its fmt controls how each value is represented. Use pandas if you already need DataFrame operations or column labels. Use csv.writer if rows need custom processing or you need Python’s CSV quoting rules. The built-in writer handles commas and quotes in fields more safely than joining values into strings yourself.
A one-dimensional array is treated as a column vector by savetxt, so it writes one value per line. To write those values across a single CSV row, reshape the array to (1, -1) before saving. The csv.writer loop below assumes a two-dimensional array: each iterated row is itself iterable. For one-dimensional input, use writer.writerow(data) to write one row, or iterate over the values and call writer.writerow([value]) to write one value per row. A CSV file has no native representation for three dimensions. Reshape a 3D array into rows and columns or flatten it, choosing an ordering that your reader can reconstruct. Do not let flattening silently define the data layout.
Save a NumPy array with numpy.savetxt()
The format '%d' is suitable for the integer values shown. For floating-point data, choose a format such as '%.3f' when three digits after the decimal point are sufficient; formatting can round values, so select precision for the data you need to preserve. A different separator, such as ';' or '\t', can be passed as delimiter when the receiving tool expects it.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6]])
with TemporaryDirectory() as directory:
path = Path(directory) / "array.csv"
np.savetxt(path, data, delimiter=",", fmt="%d")
print(path.read_text(), end="")
1,2,3
4,5,6
Save a NumPy array with pandas
Convert the array to a DataFrame, then call to_csv(). By default, pandas writes the DataFrame index and column names; set index=False and header=False when the file should contain only the array values. Leave or supply those fields when they are meaningful labels for the recipient.
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
import pandas as pd
data = np.array([[1, 2, 3], [4, 5, 6]])
with TemporaryDirectory() as directory:
path = Path(directory) / "array.csv"
pd.DataFrame(data).to_csv(path, index=False, header=False)
print(path.read_text(), end="")
1,2,3
4,5,6
Write rows with Python’s csv module
csv.writer writes each iterable row and escapes fields when CSV syntax requires it. Open the file with newline=""; this lets the CSV module manage newline characters and avoids extra blank lines on platforms with newline translation. The following uses the array’s rows directly.
from pathlib import Path
from tempfile import TemporaryDirectory
import csv
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6]])
with TemporaryDirectory() as directory:
path = Path(directory) / "array.csv"
with path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
for row in data:
writer.writerow(row)
print(path.read_text(), end="")
1,2,3
4,5,6
To append rows, open the destination in append mode ("a") and write only the new rows. Ensure their column order and number match the existing file; append mode does not validate or add a header for you. For a one-dimensional input, choose whether it represents one row or one value per row and reshape or wrap it accordingly.
Understand the limits of ndarray.tofile()
ndarray.tofile() is an array method, but it is not a CSV writer. It writes the array’s elements in flattened order and does not preserve the original shape or row-and-column structure. A comma separator can produce delimited text, but the file still cannot tell a reader the original dimensions. Its output representation also depends on the chosen format; a single line by itself does not mean numeric precision was lost. Prefer savetxt, pandas, or csv.writer when you need an explicit CSV layout.
Write CSV text manually only for simple data
For a small, known two-dimensional array containing simple numeric values, Python string formatting can create rows directly. This approach assumes the shape and values are suitable for plain text. Building the full result with join uses memory proportional to the output size, and manual joining does not handle values containing commas, quotes, or line breaks according to CSV rules. Use csv.writer for general data or text fields.
from pathlib import Path
from tempfile import TemporaryDirectory
data = [[1, 2, 3], [4, 5, 6]]
with TemporaryDirectory() as directory:
path = Path(directory) / "array.csv"
content = "\n".join(",".join(str(value) for value in row) for row in data)
path.write_text(content + "\n", encoding="utf-8")
print(path.read_text(), end="")
1,2,3
4,5,6