Home  >  Article  >  Backend Development  >  How Do I Save a 2D NumPy Array as a Human-Readable CSV File?

How Do I Save a 2D NumPy Array as a Human-Readable CSV File?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 10:15:02336browse

How Do I Save a 2D NumPy Array as a Human-Readable CSV File?

Saving a 2D NumPy Array to a Human-Readable CSV File

To output a 2D NumPy array into a human-readable CSV (Comma-Separated Values) file, utilize the numpy.savetxt function. This function exports an array to a text file in a format that can be easily understood by humans.

Implementation:

Python code to illustrate this process:

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

In this example, the 2D array a contains a matrix of numbers. The numpy.savetxt function is invoked, specifying the filename "foo.csv" as the destination. The delimiter argument sets a comma as the separator between the values.

Output:

The saved CSV file, "foo.csv", will have the following contents:

1,2,3
4,5,6
7,8,9

This represents the values of the NumPy array in a human-readable format, making it easy to analyze, share, and further process.

The above is the detailed content of How Do I Save a 2D NumPy Array as a Human-Readable CSV File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn