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

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.

Similar Reads

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....

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

...

Convert a NumPy array into a CSV using numpy.savetxt()

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

Convert a NumPy array into a CSV using file handling

...

Conclusion

The numpy.savetxt() method is used to save a NumPy array to a text file....

Contact Us