Convert a NumPy array into a csv file

In this article, we are going to see different methods to save an NumPy array into a CSV file. CSV file format is the easiest and useful format for storing data

There are different methods by which we can save the NumPy array into a CSV file

Method 1: Using Dataframe.to_csv().

This method is used to write a Dataframe into a CSV file.

Example: Converting the array into pandas Dataframe and then saving it to CSV format.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[[ 1  2  3  4  5]
[ 6  7  8  9 10]]

Method 2: Using numpy_array.tofile().

This method is used to write an array into the file.

Example: Create an array then save into a CSV file.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# import the necessary library
import numpy as np
  
# create a dummy array
arr = np.arange(1,11)
  
# display the array
print(arr)
  
# use the tofile() method 
# and use ',' as a separator
# as we have to generate a csv file
arr.tofile('data2.csv', sep = ',')

chevron_right


Output:



[ 1  2  3  4  5  6  7  8  9 10]

Method 3: Using numpy.savetext().

This method is used to save an array to a text file.

Example: Create an array then save as a CSV file.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 = ",")

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.