There is a case when you want to save or export numpy array for future use. To complete this task there are many methods and I will discuss these methods. In this entire content you will know how to convert numpy array to csv file using various approches.
Various Methods to convert numpy array to csv file
Method 1: Converting numpy array to csv file using numpy.savetxt()
In this method I will use the numpy.savetxt() function for conversion. It will take input array and convert to it csv file. Execute the below code.
import numpy as np array = np.array([[10,20,30],[40,50,60],[70,80,90]],dtype="int64") np.savetxt("my_array.csv",array,delimiter=",")
In the above code I am first creating a numpy array using the np.array() method. Then saving this array to disk with the name “my_array.csv“.
If you open the excel file then you will get the following output.
This method works fine for numerical data. But if you array has strings in it then you have to also pass the parameter fmt=’%s’ inside the numpy.savetxt() method.
Method 2: Convert array to csv file using Dot operator and tofile() method.
If you want to save the entire numpy array values in one row then this method is for you. The syntax for it is your_numpy_array.tofile().
Run the following code to save the array.
import numpy as np array = np.array([[10,20,30],[40,50,60],[70,80,90]],dtype="int64") array.tofile("my_array.csv",sep=',')
Here I am saving the array as my_array.csv file. If you open the CSV file then you will get the output as below.
Method 3: Convert Numpy array to csv file using Pandas Module
The another method for converting numpy array to csv file is Pandas python package. There is a function to do so and that is pandas.to_csv().
But the first thing you have to do is to convert numpy array to pandas dataframe. Then use the method to_csv() method to export array to CSV file.
Execute the following code.
import numpy as np import pandas as pd array = np.array([[10,20,30],[40,50,60],[70,80,90]]) df = pd.DataFrame(array) df.to_csv("my_array_pandas.csv")
When you will look into your folder then you will see the CSV file with the name “my_array_pandas”.
This method also contain row and column index ( 0,1,2). To remove it you have to pass header=None, index=None inside the to_csv() method.
If you run the code given below you will get the different record in csv than above.
These are the methods I have agreegated for you to convert array to csv file. You can use any method according to your requirement. Like if you are efficent in numpy module then go for method 1 and 2. The second method is the fast one to save it to a CSV File but it has limitation also. And if you are confident in Pandas module then go for the third method.
Hope this tutorial has cleared all the queries regarding conversion of numpy arry to csv file. Even if you have any doubt then you can contact us.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.