Open In App

Convert a NumPy array into a CSV file

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Using DataFrame.to_csv() method
  2. Using NumPy_array.tofile() method
  3. Using NumPy.savetxt() method
  4. Using File Handling operations

Let’s understand these methods better with examples.

Convert a NumPy array into a CSV using Dataframe.to_csv()

The DataFrame.to_csv() method is used to write a Dataframe into a CSV file. 

To use DataFrame.to_csv() we have to first convert the NumPy array into pandas DataFrame and then save it to CSV format.

Example

Python3




import pandas as pd
import numpy as np
  
# create a dummy array
arr = np.arange(1,11).reshape(2,5)
print(arr)
  
# convert array into dataframe
DF = pd.DataFrame(arr)
  
# save the dataframe as a csv file
DF.to_csv("data1.csv")


Output:

Convert a NumPy array into a csv file

 

Convert a NumPy array into a CSV using numpy_array.tofile()

This method is used to write a NumPy array into the file. 

The tofile() method allows us to save the NumPy array to a CSV file by calling the function with the NumPy array object and passing the CSV file_name and separator to the function.

Example

Python3




import numpy as np
arr = np.arange(1,11)
print(arr)
  
# use the tofile() method 
# and use ',' as a separator
arr.tofile('data2.csv', sep = ',')


Output:

Convert a NumPy array into a csv file

 

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:

NumPy array converted into CSV file

Convert a NumPy array into a CSV using file handling

File handling operations might be the easiest way to convert a NumPy array to a CSV file.

In Python, the str.format function is used to format strings. It inserts one or more replacement fields and placeholders, denoted by a pair of curly braces {}, into a string. The values supplied to the format function are inserted into these placeholders, resulting in a new string that includes the original input string and the formatted values.

The with keyword in Python is used in file handling operations. It ensures that the file is properly closed after it is no longer needed. This is particularly useful when writing to a CSV file, as it helps to prevent data corruption or loss. Here’s an example:

Example

Python3




# import numpy library
import numpy
  
# create an array
a = numpy.array([[1, 6, 4],
                [2, 4, 8],
                [3, 9, 1], 
                [11, 23, 43]])
  
# save array into csv file
rows = ["{},{},{}".format(i, j, k) for i, j, k in a]
text = "\n".join(rows)
  
with open('data3.csv', 'w') as f:
    f.write(text)


Output:

Convert a NumPy array into a csv file

Also Read: How to Read CSV Files with NumPy?

Conclusion

Exporting the NumPy array into a CSV file is often required to save or share your data. Python offers many ways to save NumPy arrays into a CSV file. We have discussed four methods to convert a NumPy array into a CSV file. 

In this tutorial, we have explained 4 easy methods to convert a NumPy array into a CSV file with examples and explanations. You can use any method you feel comfortable with.



Last Updated : 02 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads