Use np.savetxt("output.csv", arr, delimiter=",") (passing fmt="%.6f" or fmt="%d" for clean number formatting and header="col1,col2", comments="" when adding column names) to export 1D or 2D homogeneous numeric NumPy arrays directly to a CSV file—or convert via pd.DataFrame(arr).to_csv("output.csv", index=False) when your array mixes strings and numbers, contains missing values, or needs high-speed I/O on large datasets.
Basic Example
import numpy as np
arr = np.array([
[1, 2.5, 3.14159],
[4, 5.0, 6.28318],
[7, 8.75, 9.42477],
])
# 1. Recommended (stdlib NumPy): Save 2D array with comma delimiter & clean format
np.savetxt(
"metrics.csv",
arr,
delimiter=",",
fmt="%.4f", # Prevents verbose scientific notation (e.g., 2.500000000000000000e+00)
header="id,score,ratio", # Optional column header row
comments="", # Removes default "# " prefix from the header line
)
# 2. Save mixed integer + float columns cleanly by passing a per-column format list:
np.savetxt(
"mixed_metrics.csv",
arr,
delimiter=",",
fmt=["%d", "%.2f", "%.4f"], # First column as integer, second as 2 decimals, third as 4 decimals
header="id,score,ratio",
comments="",
)
Key Details & Edge Cases
- Always pass
delimiter=","(default is a single space" "):- Calling
np.savetxt("data.csv", arr)withoutdelimiter=","writes space-separated values rather than comma-separated values despite the.csvfilename.
- Calling
- Always pass
comments=""when specifyingheader="...":- By default,
np.savetxtprepends"# "to the header line (id,score,ratio), which breaks downstream CSV parsers (pandas.read_csv, Excel, SQL loaders) by turning the first column name into"# id". Settingcomments=""writes a clean standard CSV header.
- By default,
- Default scientific notation (
fmt="%.18e"):- Without
fmt=,np.savetxtformats every number as 18-digit scientific notation (1.000000000000000000e+00). Passfmt="%.6f"(orfmt="%g"to strip trailing zeros automatically) for compact, human-readable output.
- Without
- 3D+ arrays raise
ValueError: Expected 1D or 2D array, got 3D array instead:- CSV files are strictly 2-dimensional tables. Reshape a 3D/N-D array first (
arr.reshape(-1, arr.shape[-1])) or save in native binary.npy/.npzformat (np.save("data.npy", arr)) if you need to preserve multi-dimensional shape and exact binary precision.
- CSV files are strictly 2-dimensional tables. Reshape a 3D/N-D array first (
- String / object arrays require
fmt="%s"(orpandas.DataFrame.to_csv()):- Calling
np.savetxton a string orobjectarray withoutfmt="%s"raisesTypeError: Mismatch between array dtype ('<U5') and format specifier ('%.18e'). Furthermore,np.savetxtdoes not quote fields containing commas or newlines—usepd.DataFrame(arr).to_csv("out.csv", index=False)whenever text cells may contain commas, quotes, orNaNvalues.
- Calling
Comparison of Methods for Saving NumPy Arrays to Disk
| Method | Output Format | Supports String / Mixed Dtypes & Quoting? | Speed on Large Arrays (1M rows) |
Best Used When |
|---|---|---|---|---|
np.savetxt(..., delimiter=",") (Pure NumPy) |
Plain-text CSV | Basic (fmt="%s" only; no CSV comma escaping) |
Slow (Python-level row formatting loop) | Exporting small-to-medium 1D/2D numeric arrays with zero extra dependencies. |
pd.DataFrame(arr).to_csv(..., index=False) |
Standard RFC-4180 CSV | Yes (auto-quotes commas/newlines, handles NaN) |
Fast (C/Arrow CSV writer) | Large arrays, mixed numeric/string columns, or files opened in Excel/BI tools. |
np.save("arr.npy", arr) |
Binary .npy |
Yes (preserves exact dtype and N-D shape) |
Fastest (raw memory dump) | Caching intermediate arrays between Python/NumPy scripts without precision loss. |
You must log in or register to comment.
