As we know that Numpy is one of the premium libraries in Python available for numerical computations. You can easily create Numpy arrays in Python and you can convert Numpy arrays to different file formats. In this article, we will see how to convert a Numpy array to a CSV file.

We have 3 methods to convert Numpy array to csv file. Let’s see each of them in this article.

1. Convert Numpy array to csv using dataframe.tocsv()

In this method, we will convert the Numpy array to a CSV file using the function data frame.tocsv(). First, we have to create an array then we will pass this array to the mentioned function to convert to a CSV file in Python.

#Imports the required libraries 
import numpy as np
import pandas as pd

#Creates an array 
test_array = np.arange(0,15).reshape(3,5)
#Prints an array
print(test_array)

#Converting array to dataframe
sample_df = pd.DataFrame(test_array)

#Conveting array to csv file 
sample_df.to_csv('test_file.csv')
convert numpy

Fantastic! This is how method one works. In this, we have created an array and then with the help of pandas library we have converted that array into a data frame and then finally we have converted the data frame to CSV file.

2. Convert an array to csv file using Numpy_array.tofile()

We can use the above example for this instance also. The numpy_array.tofile() will help you in the saving the data as csv file.

Let’s see how it works.

#Import required libraries
import numpy as np
import pandas as pd

#creating an array
test_array = np.arange(0,15).reshape(3,5)

#Prints the array
print(test_array)

#Covnerths the data to csv file
test_array.tofile('test_file2.csv',sep = ',')
convert numpy array to csv

As you can see in the above output, the Numpy array is converted in to a csv file and stored in the PC.

3. Convert the Numpy array to file using numpy.savetext() function.

This function is mainly used to store the Numpy array to the csv file. Let’s see how this function works.

# import numpy library 
import numpy 
  
# create an array 
a = numpy.array([[1, 6, 4], 
                 [2, 4, 8], 
                 [3, 9, 1]]) 
  
#Deploying to CSV
numpy.savetxt("test_file3.csv", a,  
              delimiter = ",")
convert numpy array to csv

Wrapping Up

Numerical Python or Numpy is very useful for numerical calculations. You can do precise mathematical computations using the Numpy.

Python supports 3 methods through which you can easily export your array to CSV files. All these functions have been illustrated in the above sections.

That’s all for now. Happy Learning!!!