Save numpy array as csv – How to save Numpy Array to a CSV File using numpy.savetxt() in Python? | Savetxt Function’s Working in Numpy with Examples

Save numpy array as csv: NumPy arrays are very essential data structures for working with data in Python, machine learning models. Python’s Numpy module provides a function to save a numpy array to a txt file with custom delimiters and other custom options. In this tutorial, we will discuss the procedure of how to save Numpy Array to a CSV File with clear steps.

numpy.savetxt() Function

Save numpy array to csv: The numpy.savetxt() function is the counterpart of the NumPy loadtxt() function and can save arrays in delimited file formats such as CSV. Save the array we created with the following function call:

Synatx : numpy.savetxt(fname, array_name, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)

Where,

  • fname: If the filename ends in .gz, the file is automatically saved in compressed gzip format. The loadtxt() function can understand gzipped files transparently.
  • arr_name: It indicates data to be saved like 1D or 2D numpy array.
  • fmt: It refers to a formatting pattern or sequence of patterns, which will be used while saving elements to file.
  • delimiter: It is optional, refers to string or character to be used as element separator
  • newline: It is optional, refers to string or character to be used as line separator
  • header: It refers to a string that is written at the beginning of the file.
  • footer: It refers to a string that to be written at the end of the txt file.
  • comments: It refers to a custom comment marker, where the default is ‘#’. It will be pre-appended to the header and footer.

How to save Numpy Array to a CSV File using numpy.savetxt() in Python?

Numpy save to CSV: One of the most common file formats for storing numerical data in files is the comma-separated variable format or CSV in Short. Usually, input data are stored in CSV Files as it is one of the most convenient ways for storing data.

Savetxt function is used to save Numpy Arrays as CSV Files. The function needs a filename and array as arguments to save an array to CSV File. In addition, you need to mention the delimiter; for separating each variable in the file or most commonly comma. You can set via the “delimiter” argument.

Example Program on How to Save a Numpy Array to a CSV File

#Program :

import numpy as np
def main():
   # Numpy array created with a list of numbers
   array1D = np.array([9, 1, 23, 4, 54, 7, 8, 2, 11, 34, 42, 3])
   print('Real Array : ', array1D)
   print('<** Saved 1D Numpy array to csv file **>')
   # Save Numpy array to csv
   np.savetxt('array.csv', [array1D], delimiter=',', fmt='%d')
   print('*** Saving 1D Numpy array to csv file with Header and Footer ***')
   # Saving Numpy array to csv with custom header and footer
   np.savetxt('array_hf.csv', [array1D], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer')

   print('*** Saving 2D Numpy array to csv file ***')
   # A 2D Numpy array list of list created
   array2D = np.array([[111, 11, 45, 22], [121, 22, 34, 14], [131, 33, 23, 7]])
   print('2D Numpy Array')
   print(array2D)
   # Saving 2D numpy array to csv file
   np.savetxt('2darray.csv', array2D, delimiter=',', fmt='%d')
   # Saving 2nd column of 2D numpy array to csv file
   np.savetxt('2darray_column.csv', [array2D[:,1]], delimiter=',', fmt='%d')
   # Saving 2nd row of 2D numpy array to csv file
   np.savetxt('2darray_row.csv', [array2D[1] ], delimiter=',', fmt='%d')

   # Creating the type of a structure
   dtype = [('Name', (np.str_, 10)), ('Marks', np.float64), ('GradeLevel', np.int32)]
   #Creating a Strucured Numpy array
   structuredArr = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6), ('Riti', 88.8, 7)], dtype=dtype)
   print(structuredArr)
   # Saving 2D numpy array to csv file
   np.savetxt('struct_array.csv', structuredArr, delimiter=',', fmt=['%s' , '%f', '%d'], header='Name,Marks,Age', comments='')
if __name__ == '__main__':
  main()

Python Program for Saving Numpy Array to a CSV File

Output:

Real Array :  [ 9  1 23  4 54  7  8  2 11 34 42  3]
<** Saved 1D Numpy array to csv file **>
<** Saved 1D Numpy array to csv file with custom  Header and Footer **>
<** Save 2D Numpy array to csv file **>
* 2D Numpy Array *
[[111  11  45  22]
[121  22  34  14]
[131  33  23   7]]
[('Rags', 33.3, 3) ('Punit', 44.4, 5) ('Drishti', 66.6, 6)  ('Ritu', 88.8, 7)]

The Passed Delimeter ‘,’ will change to CSV Format. In addition, the format string %d passed will store the elements as integers. By default, it will store numbers in float format. Keep in mind that if you don’t mention [] around numpy array to change it to list while passing numpy.savetxt() comma delimiter willn’t work and uses ‘\n’ by default. Thus, surrounding array by [] i.e. [arr] is mandatory.

Save 1D Numpy array to CSV file with Header and Footer

Python save array to csv: In order to add comments to the header and footer while saving to a CSV File, we can pass the Header and Footer Parameters as such

# Save Numpy array to csv with custom header and footer
np.savetxt('array_hf.csv', [arr], delimiter=',', fmt='%d' , header='A Sample 2D Numpy Array :: Header', footer='This is footer')

Usually, By default comments in both the header and footer are pre-appended by ‘#’. To change this we can pass the parameter comments like comments=’@’.

Final Words

Numpy savetxt can be an extremely helpful method for saving an array to CSV File. If you want to manipulate or change the existing data set this can be a great method. If you have any queries don’t hesitate to ask us via comment box so that we can get back to you at the soonest possible. Bookmark our site for the latest updates on Python, Java, C++, and Other Programming Languages.