How to Write NumPy Array to CSV in Python
-
Use a
pandas
DataFrame to Save a NumPy Array in a CSV File -
Use the
numpy.savetxt()
Function to Save a NumPy Array in a CSV File -
Use the
tofile()
Function to Save a NumPy Array in a CSV File - Use File Handling Methods to Save a NumPy Array in a CSV File
In this tutorial, we will discuss how to store a numpy array in a CSV file.
Use a pandas
DataFrame to Save a NumPy Array in a CSV File
In this method, we will first save the array in a pandas
DataFrame and then convert this DataFrame to a CSV file.
The following code shows how we can achieve this.
import pandas as pd
import numpy as np
a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
pd.DataFrame(a).to_csv("sample.csv")
The pd.DataFrame
function stores the array in a DataFrame, and we simply export it to a CSV file using the to_csv()
function.
Use the numpy.savetxt()
Function to Save a NumPy Array in a CSV File
The savetxt()
function from the numpy module can save an array to a text file. We can specify the file format, delimiter character, and many other arguments to get the final result in our desired format.
In the following code, we save an array in a CSV file using this function.
import numpy as np
a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
np.savetxt("sample.csv", a, delimiter=",")
Use the tofile()
Function to Save a NumPy Array in a CSV File
The tofile()
function allows us to write an array to a text or binary file. However, this method has many drawbacks. It is more like a convenience function for quick storage of array data. The precision of information is lost as it stores everything in a single line, so this method is not a good choice for files intended to archive data. Some of these problems can be overcome by outputting the data as text files at the expense of speed and file size.
The following code demonstrates the use of this function.
import numpy as np
a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
a.tofile("sample.csv", sep=",")
Use File Handling Methods to Save a NumPy Array in a CSV File
We can use traditional file handling methods, but it is not advisable to use them since such methods require many modifications depending on the array’s shape and can consume a lot of memory.
The following code shows an example of this method.
a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
csv_rows = ["{},{},{}".format(i, j, k) for i, j, k in a]
csv_text = "\n".join(csv_rows)
with open("sample.csv", "w") as f:
f.write(csv_text)
We unpack the array into a list of rows and then return a single string by joining this list using the join()
function. We then write this string to a CSV file.
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn