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

In this article we will discuss how to save 1D & 2D Numpy arrays in a CSV file with or without header and footer.

numpy.savetxt()

Python’s Numpy module provides a function to save numpy array to a txt file with custom delimiters and other custom options i.e.

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

Arguments:

  • arr : 1D or 2D numpy array (to be saved)
  • fmt : A formatting pattern or sequence of patterns, that will be used while saving elements to file.
    • If a single formatter is specified like ‘%d’ then it will be applied to all elements.
    • In case of 2D arrays, a list of specifier i.e. different for each column. (Optional)
  • delimiter : String or character to be used as element separator (Optional)
  • newline : String or character to be used as line separator (Optional)
  • header : String to be written at the beginning of the txt file.
  • footer : String to be written at the end of the txt file.
  • comments : Custom comment marker , default is ‘#’. Will be pre-appended to the header and footer.

Let’s use this to save 1D and 2D numpy arrays to a csv file.

Save Numpy array to CSV File using using numpy.savetxt()

First of all import Numpy module i.e.

import numpy as np

Now suppose we have a 1D Numpy array i.e.

# Create a Numpy array from list of numbers
arr = np.array([6, 1, 4, 2, 18, 9, 3, 4, 2, 8, 11])

It will save this numpy array to csv file with name ‘array.csv‘. Contents of this file will be like,

# Save Numpy array to csv
np.savetxt('array.csv', [arr], delimiter=',', fmt='%d')

It will create a csv file with name ‘array.csv’ and store contents of numpy array in it i.e.

6,1,4,2,18,9,3,4,2,8,11

We passed the delimiter ‘,’ to make it in csv format. Also passed the format string as ‘%d’, so that it can store elements as integer. By default it will store numbers in float format. Also not that if you don’t surround numpy array by this [] i.e. convert it to list while passing it to numpy.savetxt() then comma delimiter will not work, it will use ‘\n’ as delimiter by default. So, surrounding array by [] i.e. [arr] is must.

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

If you want to add comments in header and footer while saving the numpy array to csv file, then we can pass the header and footer parameters i.e.

# 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')

It will create a file with name ‘array_hf.csv‘ and following contents,

# A Sample 2D Numpy Array :: Header
6,1,4,2,18,9,3,4,2,8,11
# This is footer

By default comments in both header and footer will be pre-appended by ‘#’. If we want to change this then we can pass the parameter comments like comments=’@’

Save 2D Numpy array to CSV File

Let’s create a 2D numpy array from list of list i.e.

# Create a 2D Numpy array list of list
arr2D = np.array([[11, 12, 13, 22], [21, 7, 23, 14], [31, 10, 33, 7]])

Contents of this 2D numpy array is,

[[11 12 13 22]
 [21  7 23 14]
 [31 10 33  7]]

Now let’s save this 2D numpy array to csv file with name ‘2darray.csv‘ i.e.

# Save 2D numpy array to csv file
np.savetxt('2darray.csv', arr2D, delimiter=',', fmt='%d')

Contents of the file ‘2darray.csv’ will be,

11,12,13,22
21,7,23,14
31,10,33,7

Also, instead of saving complete 2D numpy array to a csv file, if we want we can save single or multiple columns or rows only.

Save a column of 2D numpy array to csv file

# Save 2nd column of 2D numpy array to csv file
np.savetxt('2darray_column.csv', [arr2D[:,1]], delimiter=',', fmt='%d')

Let’s check contents of the file ‘2darray_column.csv‘,

12,7,10

Save a row of 2D numpy array to csv file

# Save 2nd row of 2D numpy array to csv file
np.savetxt('2darray_row.csv', [arr2D[1] ], delimiter=',', fmt='%d')

Let’s check contents of the file ‘2darray_row.csv‘,

21,7,23,14

Save a Structured Numpy array in csv file by using list of formatting options

Let’s create a structured numpy array where each element in numpy array will contain a string, float and integer i.e.

# 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)

Contents of this structured numpy array is,

[('Sam', 33.3, 3) ('Mike', 44.4, 5) ('Aadi', 66.6, 6) ('Riti', 88.8, 7)]

Now to store this structured numpy array to csv file using savetxt() we need to pass list of formatting options i.e.

# Save 2D numpy array to csv file
np.savetxt('struct_array.csv', structuredArr, delimiter=',', fmt=['%s' , '%f', '%d'], header='Name,Marks,Age', comments='')

Contents of the file ‘struct_array.csv‘ will be,

Name,Marks,Age
Sam,33.300000,3
Mike,44.400000,5
Aadi,66.600000,6
Riti,88.800000,7

As each element in our numpy array was a combination of string, float and integer therefore while saving it to csv file we pass the formatting options as =[‘%s’ , ‘%f’, ‘%d’]

Complete example is as follows:

import numpy as np

def main():

   # Create a Numpy array from list of numbers
   arr = np.array([6, 1, 4, 2, 18, 9, 3, 4, 2, 8, 11])

   print('Original Array : ', arr)

   print('*** Save 1D Numpy array to csv file ***')

   # Save Numpy array to csv
   np.savetxt('array.csv', [arr], delimiter=',', fmt='%d')

   print('*** Save 1D Numpy array to csv file with Header and Footer ***')

   # 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')


   print('*** Save 2D Numpy array to csv file ***')

   # Create a 2D Numpy array list of list
   arr2D = np.array([[11, 12, 13, 22], [21, 7, 23, 14], [31, 10, 33, 7]])

   print('2D Numpy Array')
   print(arr2D)

   # Save 2D numpy array to csv file
   np.savetxt('2darray.csv', arr2D, delimiter=',', fmt='%d')

   # Save 2nd column of 2D numpy array to csv file
   np.savetxt('2darray_column.csv', [arr2D[:,1]], delimiter=',', fmt='%d')

   # Save 2nd row of 2D numpy array to csv file
   np.savetxt('2darray_row.csv', [arr2D[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)

   # Save 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()

Output:

Original Array :  [ 6  1  4  2 18  9  3  4  2  8 11]
*** Save 1D Numpy array to csv file ***
*** Save 1D Numpy array to csv file with Header and Footer ***
*** Save 2D Numpy array to csv file ***
2D Numpy Array
[[11 12 13 22]
 [21  7 23 14]
 [31 10 33  7]]
[('Sam', 33.3, 3) ('Mike', 44.4, 5) ('Aadi', 66.6, 6) ('Riti', 88.8, 7)]

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top