Convert a NumPy array into a CSV using numpy.savetxt()
The numpy.savetxt() method is used to save a NumPy array to a text file.
We can save the NumPy array to a CSV file by passing the file name, NumPy array, and the delimiter in the function numpy.savetxt().
Python3
# import numpy library import numpy # create an array a = numpy.array([[ 1 , 6 , 4 ], [ 2 , 4 , 8 ], [ 3 , 9 , 1 ]]) # save array into csv file numpy.savetxt( "data3.csv" , a, delimiter = "," ) |
Output:
Convert a NumPy array into a CSV file
After completing your data science or data analysis project, you might want to save the data or share it with others. Exporting a NumPy array to a CSV file is the most common way of sharing data.
CSV file format is the easiest and most useful format for storing data and is convenient to share with others. So in this tutorial, we will see different methods to convert a NumPy array into a CSV file.
Different methods to convert a NumPy array to a CSV file are:
- Using DataFrame.to_csv() method
- Using NumPy_array.tofile() method
- Using NumPy.savetxt() method
- Using File Handling operations
Let’s understand these methods better with examples.