Home >Backend Development >Python Tutorial >How to Export NumPy Arrays to Human-Readable CSV Files?

How to Export NumPy Arrays to Human-Readable CSV Files?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 20:12:03316browse

How to Export NumPy Arrays to Human-Readable CSV Files?

Exporting NumPy Arrays to Human-Readable CSV Files

Storing data in human-readable formats is crucial for data analysis and visualization. To export a 2D NumPy array into a CSV file, the numpy.savetxt function comes in handy.

The numpy.savetxt function saves a given NumPy array to a text file, such as CSV (Comma-Separated Values). The CSV format is widely used and easily readable by humans.

To use numpy.savetxt:

  1. Import the NumPy module: import numpy.
  2. Create your NumPy array.
  3. Call numpy.savetxt(filename, array, delimiter=",").

The filename parameter specifies the output CSV file's name. The array parameter is the NumPy array you want to save. Finally, the delimiter parameter specifies the character to use for separating values within the CSV file. By default, a comma is used.

For example, the following code saves a 2D NumPy array to a CSV file named "foo.csv":

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

This will create a CSV file with the following contents:

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

The above is the detailed content of How to Export NumPy Arrays to 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