How to save array as csv file with Numpy?

In this tutorial, we’ll learn how to save a NumPy array as a CSV file using the savetxt method. Saving data as a CSV file is a common operation in data science and analysis, and NumPy provides a straightforward way to accomplish this.

Numpy savetxt as csv

How to use python savetxt method

Numpy savetxt function let us save Numpy array as text file. We can save an array as comma separated values as well.

See also  How to reverse array in Numpy?

To save an array to csv extension file you need to use savetxt file like in the below example.

import numpy as np

my_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape(3, 3)
to_csv = np.savetxt("my_matrix.csv", my_array, delimiter=",")

Checking np.savetxt(“my_matrix.csv”, my_array, delimiter=”,”) you may know the syntax of savetxt method.

  • first one is file name, you can also put a path to the file here
  • my_array is an array to would like to dump as csv
  • delimiter is a comma since it is csv file
  • See also  How to Generate Random Integers in Range with Numpy

    Using the NumPy savetxt method, you can save your data as CSV or other text-based file formats like plain text files.

    Now, if you check your working directory, you will find the “my_matrix.csv” file containing your NumPy array in CSV format.

    By mastering this method, you can efficiently save your data for further analysis or sharing with others, making NumPy a valuable tool for data manipulation tasks in Python.

    See also  How to convert numpy to xyz file?