Home  >  Article  >  Backend Development  >  How to Save NumPy Arrays as Human-Readable CSV Files?

How to Save NumPy Arrays as Human-Readable CSV Files?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 07:06:02418browse

How to Save NumPy Arrays as Human-Readable CSV Files?

Saving NumPy Arrays as Human-Readable CSV Files

NumPy offers a convenient way to export data into a human-readable format suitable for various use cases. To achieve this, we leverage the numpy.savetxt function.

To dump a 2D NumPy array into a CSV file, follow these steps:

  1. Import NumPy.
  2. Convert your array to a NumPy array using numpy.asarray().
  3. Specify the desired file name and delimiter for the CSV file.
  4. Use numpy.savetxt() to save the array to the specified file.

Example:

Consider the following 2D NumPy array:

a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])

To export this array to a CSV file named "foo.csv" with a comma separator, use the following code:

import numpy
numpy.savetxt("foo.csv", a, delimiter=",")

This will create a CSV file containing the array's values in a human-readable format:

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

The above is the detailed content of How to Save NumPy Arrays as Human-Readable CSV Files?. 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