Dump a NumPy array into a csv file
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Writing a NumPy array to CSV is a common export step when you want to inspect numeric data outside Python or hand it to another tool. The simplest solution for plain numeric arrays is usually numpy.savetxt. If you need headers, indexes, or more table-like behavior, converting to a Pandas DataFrame and using to_csv is often more convenient.
The Straight NumPy Solution: savetxt
For numeric arrays, numpy.savetxt is the standard direct tool.
This writes a comma-separated file with one row per array row.
If you need a specific numeric format, use fmt.
That prevents the default scientific or high-precision formatting from making the CSV harder to read.
Writing Integer Arrays
If the data is integer-based, match the format string to the data.
Using %d avoids writing integers as floating-point values.
Add a Header When Needed
CSV exports often need column names.
The comments='' part prevents NumPy from prefixing the header with #, which many CSV consumers do not want.
Use Pandas for More Table-Like Output
If you need labels, indexes, or more control over CSV structure, Pandas is often the better tool.
This is especially useful when the array is really tabular data rather than just raw matrix output.
Choose Delimiters and Formats Deliberately
CSV usually means commas, but many tools expect semicolons, tabs, or locale-specific decimal conventions. savetxt can handle those cases too.
This is useful when the receiving system is not using the default comma-separated convention.
One-Dimensional Arrays Need Attention Too
A one-dimensional array can be written directly, but the layout may not match what you expect.
This writes one value per line. If you want a single CSV row, reshape first.
Validate the Export by Reading It Back
A quick read-back check is a good way to catch delimiter or formatting mistakes.
That is especially useful when another system is going to consume the file later.
Common Pitfalls
- Using
savetxtwithoutfmtand getting numeric formatting that is harder to read than expected. - Forgetting that one-dimensional arrays write as one value per line unless reshaped.
- Writing integer data with a floating-point format or vice versa.
- Expecting CSV headers from NumPy without supplying them explicitly.
- Using raw NumPy output when the real need is a labeled table better handled by Pandas.
Summary
- Use
numpy.savetxtfor direct CSV export of numeric arrays. - Set
delimiter=','and choose an appropriatefmtfor readable output. - Add headers explicitly if the CSV should have column names.
- Reshape one-dimensional arrays if you want a single row instead of one value per line.
- Prefer Pandas
to_csvwhen labels and table-style export matter.

